Thursday, January 1, 2009

MRO magic

Here's some more less publicized evil you can accomplish with metaclasses. Here's a simple example file: (Note that although I'm using Python 3.0, this works with all new-style class supporting versions.)

How does this work? By overriding mro() on the a metaclass we can define a custom __mro__ for our class. Python will then traverse it instead of the default implementation, which is provided by type.mro().

3 comments:

Anonymous
said...

Python 2.5.1 does not accept the metaclass= syntax in the base class description at compile time, and does not accept type as a base class at runtime (since no argument is provided to the constructor).