views:

57

answers:

1

Sorry for the trivial question, but I can't find this infomation from the manual. I am developping a module for python using C api; how can I create a variabile that is seen as global from python? For example if my module is module I want to create a variable g that do 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);
+1  A: 

You can use PyObject_SetAttrString in your module's initialization routine, with first argument o being (the cast to (PyObject*) of) your module, second argument attr_name being "g", third argument v being a variable

PyObject *v = PyLong_FromLong((long) 23);

(or whatever other value of course, 23 is just an example!-).

Do remember to decref v afterwards.

There are other ways, but this one is simple and general.

Alex Martelli
thanks, can you check the full solution that I report in the question?
wiso
@wiso, yep, those 4 lines were exactly what I had in mind (except that you're naming the attribute "L" in the edit and it is "g" above in the original question, but that's no doubt just an oversight).
Alex Martelli