extending Python base class in C

harold fellermann harold.fellermann at upf.edu
Tue Jun 14 14:04:03 EDT 2005



> "harold fellermann" <harold.fellermann at upf.edu> wrote in message
> news:mailman.378.1118678951.10512.python-list at python.org...
> Hi all,
>
> I once read that it is possible to use a python base class for a C
> extension class.

On 14.06.2005, at 09:29, Grigoris Tsolakidis wrote:

> There was good article of how to do this on DDJ home page www.ddj.com

unfortunately, I could not find it yet. I managed to do the following:
I the initmodule function of my extension, I import the module and look
for the class I want to use as a base class:

PyObject *base_module = PyImport_ImportModule("module_name");
if (!base_module) return;

PyObject *base_class = PyMapping_GetItemString(
		PyModule_GetDict(base_module,"BaseClass")
	);
if (!base_class) return;


This gives me a pointer to the class I want to use as base class.
Does anyone know how to assign this to the extension class? I tried
to build a tuple (BaseClass,) and assign it (after the respective
PyType_Ready call) to CClass.__bases__ like this:

PyObject_SetAttrString(
	&cclassType,
	"__bases__",
	Py_BuildValue("(O,)",base_class)
);

but this raises a TypeError when executed during import:

TypeError: can't set attributes of built-in/extension type 
'ext_module.CClass'

Any ideas how to proceed?

- harold -

--
You can imagine the opposite
-- Maurizio Nannucci




More information about the Python-list mailing list