defining class and subclass in C

Daniel Franke franke.daniel at
Sat Jan 14 18:29:20 EST 2012

On Saturday 14 January 2012 22:15:36 Daniel Franke wrote:
> Here I'd expect "<class ''>" instead?! And I never managed a proper
> subclass :|

Found an explanation on type/class at [1]: "he difference between the two is 
whether the C-level type instance structure is flagged as having been 
allocated on the heap or not" - hu?

With this info, I went ahead and tried the code quoted below. Now I get:

>>> import cmod
<type ''>
>>> cmod.cb
<type 'cmod.cb'>
(<type 'object'>,)
>>> cmod.cb.__bases__
(<type ''>,)

which seems to make sense besides the "type" instead of "class"?!

What threw me is that I expected that I'd need to explicitly subclass the 
"object" type, from which I assumed for some reason I'd also inherit the 
.tp_new member. This is obviously not the case.

Now the last question is, how do I get the a_type of Python class to use it as 
base for "cb"?

On lives and learns.



#include <Python.h>

typedef struct {
} ca;

static PyTypeObject ca_Type = {

typedef struct {
} cb;

static PyTypeObject cb_Type = {

PyMODINIT_FUNC initcmod(void) {
  PyObject *cmod;

  ca_Type.tp_name      = "";
  ca_Type.tp_basicsize = sizeof(ca);
  ca_Type.tp_flags     = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
  ca_Type.tp_new       = PyType_GenericNew;
  ca_Type.tp_base      = &PyBaseObject_Type;

  if (PyType_Ready(&ca_Type) < 0)

  cb_Type.tp_name      = "cmod.cb";
  cb_Type.tp_basicsize = sizeof(cb);
  cb_Type.tp_flags     = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
  cb_Type.tp_base      = &ca_Type;

  if (PyType_Ready(&cb_Type) < 0)

  cmod = Py_InitModule3("cmod", NULL, "c module");
  if (cmod == NULL)

  PyModule_AddObject(cmod, "ca", (PyObject*)&ca_Type);

  PyModule_AddObject(cmod, "cb", (PyObject*)&cb_Type);

More information about the Python-list mailing list