[Python.NET] Subtyping in 'C'

Mark English Mark.English at liffe.com
Thu Dec 18 09:25:16 EST 2003

Hope someone can help because I'm stumped.

I'm trying to use the new subtyping mechanism. There is a hierarchy of 3
Base - The base type
C - Type derived from Base
D - Type derived from C

Base and C both have tp_new functions of their own. Since D doesn't
define one, it ends up with C's. (I actually initialise it this way, but
I believe that is what "PyType_Ready()" would do anyway)
Base -> tp_new = Base::New
C -> tp_new = C::New
D -> tp_new = C::New

tp_new has the following signature:
PyObject * New (PyTypeObject *ptype, PyObject *args, PyObject *kwds)

I've tried to follow the existing code and PEP 0253.

Base::New calls ptype->tp_alloc and then does some non-varying data

C::New calls:
"ptype->tp_base->tp_new(ptype, args, kwds)"
and then does some non-varying data initialisation of its own.

As stated, D doesn't have a tp_new function, so it ends up with C's.

When constructing an instance of type "D", the following happens:
C::New is called, where ptype=D. This delegates to
ptype->tp_base->tp_new, where ptype->tp_base is C.
C::New is called, where ptype=D. This carries on in a loop.

The obvious solution is to pass ptype->tp_base as the ptype parameter in
C::New like this:
"ptype->tp_base->tp_new(ptype->tp_base, args, kwds)"

The problem here is that when the tp_alloc function is called, "ptype"
points to the basemost class of the class instance we're actually trying
to initialise (in this case "Base"), and so not enough memory will be

So currently the choice lies between blowing up the stack in an infinite
loop, or initialising too small an amount of memory. Could get the
functions to call the base type functions explicitly, without going
through the tp_new pointer, but that seems kinda dirty. Thinking about
hacking the object size in the "Base" type temporarily, so that at least
I can allocate the correct amount of memory. Also not pretty but leaves
the indirection alone.

I'm using ActivePython 2.2.2 and I'd really rather not upgrade or switch

Any help, gratefully received.


The information contained in this e-mail is confidential and solely 
for the intended addressee(s). Unauthorised reproduction, disclosure, 
modification, and/or distribution of this email may be unlawful. If you 
have received this email in error, please notify the sender immediately 
and delete it from your system. The views expressed in this message 
do not necessarily reflect those of LIFFE Holdings Plc or any of its subsidiary companies.

More information about the PythonDotNet mailing list