class attributes and inner classes in C extensions

Thomas Heller theller at python.net
Fri Apr 1 13:01:59 EST 2005


harold fellermann <harold.fellermann at upf.edu> writes:

>> I am working on a C extension module that implements a bunch of
>> classes. Everything
>> works fine so far, but I cannot find any way to implement class
>> attributes or inner
>> classes. Consider you have the following lines of Python :
>>
>> class Foo :
>> 	class Bar :
>> 		pass
>>
>>      spam = "foobar"
>>
>> How can this class be translated to a C extension? Is there anything
>> comparable to
>> PyMethodDef that can be used for other attributes than functions?
>
> O.k. I found it out now, and in order to improve the knwoledge base of
> the mailing
> list, I will answer my question myself.
>
> The PyTypeObject structure has a field tp_dict that holds the
> dictionary of the class object. You can initialize it with a
> dictionary that holds class attributes.  If you provide a custom
> dictiomary, you must do so _before_ PyType_Ready() is called, because
> PyType_Ready adds other entries to this dictionary.

I think you could as well, after PyType_Ready() is called, set it
yourself with
  PyObject_SetAttrString(FooType, "Bar", FooBarType);

You *may* have to cast the FooType and FooBarType to (PyObject *), to
avoid compiler warnings.

Thomas



More information about the Python-list mailing list