问题
I'm using BoostPython for embedding Python in my C++ project but I don't understand all stuffs about Python, especially the namespace system.
Actually, I used this code:
byte_code = Py_CompileString(filedata, filename, Py_file_input);
// [...]
PyObject* res = NULL;
PyObject* main_module = PyImport_AddModule("__main__");
PyObject* global_dict = PyModule_GetDict(main_module);
PyObject* local_dict = PyDict_New();
py::object local_namespace(py::handle<>(py::borrowed(local_dict)));
// Set a user object (only for this execution)
local_namespace["user_object"] = py::ptr(&MyObject);
res = PyEval_EvalCode( byte_code, global_dict, local_dict );
Py_XDECREF(res);
Py_XDECREF(local_dict);
But When I execute a python script like:
def testB():
print("B")
def testA():
testB() # NameError: global name 'testB' is not defined
testA() # Works
testB() # Works
Okay I could used
res = PyEval_EvalCode( byte_code, global_dict, global_dict );
instead of
res = PyEval_EvalCode( byte_code, global_dict, local_dict );
But I want preserve the global_dict from any new function definition (Because when I will launch a new script, I don't want that previous function definition from a very old execution can be called !)
This is a problem about namespace, isn't it ?
回答1:
Yes, this is a namespace problem. You should look into the way Python handles scope (specifically the "self" keyword).
In short, class member variables and functions are prefixed with "self." in order to specify that they are a member of the current object's scope. "Self" is loosely similar to the "this" keyword in C++ and C#.
来源:https://stackoverflow.com/questions/19772058/boost-python-global-and-local-dictionary