[Python-Dev] PEP 253: Subtyping Built-in Types

Guido van Rossum guido@digicool.com
Sat, 21 Jul 2001 18:29:22 -0400


> I've started playing with making mxDateTime types subclassable

Cool!!!

> and have run into a few problems which the PEP does not seem
> to have answers to:
> 
> 1. Are tp_new et al. inherited by subclassed types ?

My apologies that this stuff is so underdocumented -- there's just so
*much* to be documented...  in typeobject.c, in inherit_slots(),
there's a call to COPYSLOT(tp_new), so the answer is yes.

> This is important when implementing the slot methods, since
> they may then see types other than the one for which they
> are defined (e.g. keeping a free list around will only
> work for the original types, not subclassed ones).

Yes, I've worked out a scheme to make this work, but I don't think
I've written it down anywhere yet.  If your tp_new calls tp_alloc, and
your tp_dealloc calls tp_free, then a subtype can override tp_alloc
*and* tp_free and the right thing will happen.  A subtype can also
*extend* tp_new and tp_dealloc.  (tp_new and tp_dealloc are sort-of
each other's companions, and ditto for tp_alloc and tp_free.)

> 2. In which order are the allocation/deallocation methods
> of subclass and base class called (if at all) and how
> does this depend on whether they are implemented or inherited ?

Here's the scheme.  A subtype's tp_new should call the base type's
tp_new, passing the subtype.  The base class will call tp_alloc, which
is the subtype's version.  Similar for deallocation: the subtype's
tp_dealloc calls the base type's tp_dealloc which calls tp_free which
is the subtype's version.

> 3. How can I make attributes visible in subclassed types ?
> 
> Even though I found out that I need to use the generic APIs
> PyObject_GenericGet|SetAttr() for the tp_get|setattro to
> make methods visible, attributes cannot be accessed (and this
> even though dir(instance) displays them).

Strange.  This should work.  Probably something's subtly wrong in your
setup.  Compare your code to xxsubtype.c.

> In any case, the new feature looks very promising !

Thanks!

--Guido van Rossum (home page: http://www.python.org/~guido/)