Metaclass programming in Python

I’m a few years behind, but while I knew you could modify classes in Python, it turns out you can do it conveniently as of Python 2.2.

Here’s how you can dynamically create a class:
>>> from new import classobj
>>> Foo2 = classobj('Foo2',(),{"mymethod":lambda self,x: x})
>>> Foo2().mymethod(2)

Once the class has been created, you can easily modify it as well:

>>> setattr(Foo2,'anothermethod',lambda self,x: 2*x)
>>> Foo2().anothermethod(2)

I recall that I found ways to achieve the same result by manipulating directly class objects, but this is much neater.

You can even dynamically change the class of an object:
>>> t.__class__=classobj('newFoo2', (Foo2,), {"supermethod":lambda self,x: 5*x})
>>> t.supermethod(2)

That’s pretty satisfying.

Published by

Daniel Lemire

A computer science professor at the University of Quebec (TELUQ).

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see