Vil
Vil

Reputation: 131

How can I create a static variable in a Python class via the C API?

I want to do the equivalent of

class Foo(object):
  bar = 1

using Python's C API. In other words, I want to create a Python class which has a static variable, using C.

How can I do this?

Upvotes: 8

Views: 876

Answers (2)

Vil
Vil

Reputation: 131

Found it! It's just a matter of setting the tp_dict element of the type object and filling adding entries to it for each of the static variables. The following C code creates the same static variable as the Python code above:

PyTypeObject type;
// ...other initialisation...
type.tp_dict = PyDict_New();
PyDict_SetItemString(type.tp_dict, "bar", PyInt_FromLong(1));

Upvotes: 5

joeforker
joeforker

Reputation: 41747

You can pass that source code to Py_CompileString with the appropriate flags.

If you already have the class you could use PyObject_SetAttr.

Upvotes: 2

Related Questions