I am developing a module for Python using a C API. How can I create a variable that is seen as global from Python?
For example, if my module is module, I want to create a variable g that does this job:
import module
print module.g
In particular, g is an integer.
Solution from Alex Martelli
PyObject *m = Py_InitModule("mymodule", mymoduleMethods);
PyObject *v = PyLong_FromLong((long) 23);
PyObject_SetAttrString(m, "g", v);
Py_DECREF(v);
You can use PyObject_SetAttrString in your module’s initialization routine, with first argument
obeing (the cast to(PyObject*)of) your module, second argumentattr_namebeing “g”, third argumentvbeing a variable(or whatever other value of course,
23is just an example!-).Do remember to decref
vafterwards.There are other ways, but this one is simple and general.