tags:

views:

97

answers:

2

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?

+2  A: 

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

If you already have the class you could use PyObject_SetAttr.

joeforker
Thanks for the suggestion! It seems a bit of a roundabout way to do it though - is there anything similar to PyModule_AddIntConstant for classes?
Vil
Sorry, I only just noticed that you updated your answer. Thanks again for the help.I've tried using PyObject_SetAttr, but no matter when I call it I get a TypeError with the message "can't set attributes of built-in/extension type X" (where X is my type name). Am I doing something wrong, or does this simply not work with type objects?
Vil
You should paste your code?
joeforker
I found the solution I was after in the end. Thanks a lot for your suggestions though!
Vil
A: 

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));
Vil