Subtyping a non-builtin type in C/C++

johan2sson at gmail.com johan2sson at gmail.com
Sat Aug 5 20:01:47 EDT 2006


Hi

I am trying to create a subclass of a python class, defined in python,
in C++, but I am having some problems. It all boils down to a problem
of finding the base class' type object and according to the PEP (253) I
would also need to figure out the size of the base class instance
structure, but I'm guessing that the latter can't be done in a way that
would allow me to define a structure for my own type.

The following code is what I've tried, which is an adaptation of
http://groups.google.com/group/comp.lang.python/msg/b32952c69182d366

	/* import the module that holds the base class */
	PyObject *code_module = PyImport_ImportModule("code");
	if (!code_module) return;

	/* get a pointer to the base class */
	PyObject *ic_class = PyMapping_GetItemString(
					PyModule_GetDict(code_module),
					"InteractiveConsole");
	if (!ic_class) return;

	/* assign it as base class */
	// The next line is the original code, but as far as I can understand
	// the docs for Py_BuildValue the code used is equivalent. I find it
	// to be clearer as well.
	// EmConType.tp_bases = Py_BuildValue("(O)", ic_class);

	Py_INCREF(ic_class);
	EmConType.tp_bases = ic_class;

	if (PyType_Ready(&EmConType) < 0)

This breaks an assertion in the function classic_mro called by
PyType_Ready however, specifically that on line 1000 of typeobject.c:
assert(PyClass_Check(cls)). To get there you need to fail PyType_Check
as well and indeed, at least in the debug build, cls.ob_type.tp_name is
"dict". ic_class appears to be a "classobj" before the call to
PyType_Ready. I would of course much rather have seen that it was a
"type", but I'm not sufficiently well versed in the python guts to know
if this is ok or not.

If anyone could please lend me a clue, I'd be terribly happy about it.

Thanks,
Johan




More information about the Python-list mailing list