So what is a metaclass, anyway?
That's something I've always been wondering and I guess it kind of fits the theme. So let's find out.
As always, we can start with the Wikipedia article:
In object-oriented programming, a metaclass is a class whose instances are classes. Just as an ordinary class defines the behavior of certain objects, a metaclass defines the behavior of certain classes and their instances.
Okay, so it allows you to specify various stuff about how a class works. But why isn't your grandma's plain old class definition enough for that?
(In the following, I'll focus on Python as the object-oriented language; this might well apply elsewhere too.)
Well, first of all, consistency of the type system. Since everything is an object, that 'everything' can be taken to include the class itself (for example, what is the type of obj.__class__ when obj is an object? It's the class of the object's class - the metaclass.
What is it good for? Well, you can dynamically, at runtime change an object's metaclass. That means you can basically rewrite the object's definition - one can imagine a specially crafted metaclass that just wraps around each of the original class's methods, but additionally prints out their names just before being called. Bam, logging. For any class you receive. Automagically. And so meta.
That being said, metaclasses appear to have a bad reputation. They can be quite powerful, but they're generally only used in libraries. As Tim Peters, famous in Python circles puts it:
Metaclasses are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you don't.
For additional reading check out:
Metaclasses in Five Minutes
Python metaclasses by example









