new extension type inheriting from list

Tim Peters tim.one at comcast.net
Sun Feb 1 17:21:44 CET 2004


[Robin Becker]
> Is there any example anywhere of a new style extension type that
> inherits from a built in type.

Modules/xxsubtype.c in the Python source distribution has examples of C
types inheriting from list and dict.  test_descr.py has examples of Python
types inheriting from all sorts of builin types.

> I would like to write a list based type, but although I see there
> is a tp_bases slot I suspect there's more that I need to know.

Probably <wink>.

> How does one handle the forwarding of members and methods etc.

Most of that works by magic:  the type slots you don't force are filled in
(via inheritance from tp_base) when you call PyType_Ready() during
initialization.

> How does one do explicit super etc?

You're better off not trying to override existing methods, as the overrides
may not get called.  Adding new methods to builtin types via subclassing was
the intent, and works fine.  Trying to change the behavior of existing
methods is a crapshoot, and is better done by containment than inheritance.

That said, since C doesn't support inheritance anyway, there's no generally
applicable approach to faking super at the C level, and people do all sorts
of things.  For example, if you want the length of an instance of your list
subtype in C, you could call PyList_Size(self), or cast self to the list
type and access ob_size, or go thru a tedious chain of pointer derefencing
starting with your type's tp_base.

I don't think there any examples of this in the core.  The closest it gets
is that bool inherits from int, so there are some overrides in boolobject.c.
datetime.datetime also inherits from datetime.date, but both types are
implemented in the same file so can (& do) use each other's internals
directly.





More information about the Python-list mailing list