Boost Python - Global and Local dictionary

僤鯓⒐⒋嵵緔 提交于 2021-02-05 07:49:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!