class attributes and inner classes in C extensions

harold fellermann harold.fellermann at upf.edu
Fri Apr 1 11:28:46 EST 2005


> 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.

This is my C extension of the above. It works great for me:

static PyTypeObject FooType = {
	/* ... snip ... */
	0,					// tp_dict
	/* ... snip ... */
};

static PyTypeObject FooBarType = {
	/* ... snip ... */
};

PyMODINIT_FUNC inithyper(void)
{
     /*
         the following lines add class attributes to the types tp_dict:
     */
     FooType.tp_dict = PyDict_New();
     PyDict_SetItemString(FooBarType,"Bar",(PyObject *)&FooBarType);
     
PyDict_SetItemString(FooBarType,"spam",PyString_FromString("foobar"));

     PyObject* m;
     if (PyType_Ready(&hFooType) < 0) return;
     if (PyType_Ready(&hFooBarType) < 0) return;

     m = Py_InitModule3("my_module", NULL, "some documentation");

     Py_INCREF(&FooType);
     PyModule_AddObject(m, "Foo", (PyObject *)&FooType);

     Py_INCREF(&hyper_FooBarType);
     PyModule_AddObject(m, "Bar", (PyObject *)&FooBarType);
}


Documentation for tp_dict can be found in the API:
http://docs.python.org/api/type-structs.html


- harold -

--
"2x2 = grün"
-- Heinz von Foerster




More information about the Python-list mailing list