(Presentation at the Dutch Django/web meeting)
Metaclass magic feels like magic, but it isn’t real magic. Metaclasses are ideal for frameworks and code you want to reuse.
They make web applications that have to feel like desktop apps. Very fast and responsive. TND Dataview (note: a non-opensource project he used as example for metaclasses) are fully ajax based CRUD views for Django that are very fast.
A dataview is just a view, but it subclasses Dataview
, which fires up all
sorts of metaclass magic. This is not the Meta
class on your model, but
a metaclass
is a python class that itself creates classes. Normally a class is generated
behind the scenes with type()
, but with the proper invocation, a metaclass
takes over type()
’s work. For that, the metaclass should have a
__new__()
next to the common __init__()
.
You use a metaclass by specifying an __metaclass__
attribute on one of
your classes that points at a metaclass.
A metaclass’s __new__()
method can do do everything python can do. The
possibilities are endless. You can do extra logging, you can look at the
attributes of the class and do special things to them, etc. (Note by
Reinout: django itself uses it for models, for instance).
An example: dataview’s metaclass creates the necessary URLs for your view. It creates filters based on your data. It uses declarations (=attributes on the view and on the class
A nice tutorial: http://www.ibm.com/developerworks/linux/library/l-pymeta/index.html
Dataview itself is not open source. It is not good enough yet. They could make it available. But… the main goal of his presentation is not dataview as such, but to get us enthousiastic about metaclasses.
My name is Reinout van Rees and I program in Python, I live in the Netherlands, I cycle recumbent bikes and I have a model railway.
Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):