The Don Beaudry/Jim Fulton hack
Gordon McMillan
gmcm at hypernet.com
Thu Dec 30 09:14:49 EST 1999
Dave Abrahams wrote:
>
> I've recently been crawling through the source code (trying to
> understand what all those fields in PyTypeObject really do), and
> stumbled across an explanation for what I had read about being
> able to subclass a type extension in Python: there's special code
> to make this possible!
Not really. That special code allows you to take over the
building of a new instance from Python. Subclassing a type
takes a whole lot of C code.
> I think: it would be cool to experiment with this before writing
> any C code, just to make sure I understand it. So I fire up
> Python. Since the special code is never entered if the base is a
> real class (not shown), I figure it has to be an instance:
> otherwise, how could it have an attribute called "__class__"?
Correct.
> >>> class Empty: pass
> ...
> >>> base = Empty()
> >>> base.__class__ = stupid_class
> Traceback (innermost last):
> File "<input>", line 1, in ?
> TypeError: __class__ must be set to a class
> >>>
Nope. The above magic is invoked when the "class" statement
is run. So the key is
class MyClass(magicinstance):
That is, you "derive" from an instance. The magicinstance has
nothing to do with the result. It's the magicinstance's class
that provides the magic. IOW, this was an easy way to test
out an experimental feature, not an axiom of the object model.
Look at Demo/metaclasses.
> Finally, another point. It is now possible to make extension
> classes which walk, talk, and smell just like built-in classes
Not at all. Making a type subclassable means bridging the two
different "method" mechanisms. Types have slots, classes /
instances have magic dictionaries. Take a look at
ExtensionClass from Digital Creations (comes with Zope).
Notice that it reimplements 99% of everything, and only types
of the ExtensionClass type are subclassable (so you still can't
subclass lists or dictionaries).
Most of the type-checking at the C level consists of seeing
whether the object's typeobject is (same address) some well
known typeobject. Since the methods are on the typeobject,
you can't trick the C code.
- Gordon
More information about the Python-list
mailing list