This is a hot question from Stakoverflow. http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python.
Just record the awesome discription.
Classes as objects
Before understanding metaclasses, you need to master classes in Python. And Python has a very peculiar idea of what classes are, borrowed from the Smalltalk language.
In most languages, classes are just pieces of code that describe how to produce an object. That’s kinda true in Python too:
1 2 3 4 5 6 7
But classes are more than that in Python. Classes are objects too.
As soon as you use the keyword class, Python executes it and creates an OBJECT. The instruction
1 2 3
creates in memory an object with the name ObjectCreator.
This object (the class) is itself capable of creating objects (the instances), and this is why it’s a class.
But still, it’s an object, and therefore:
- you can assign it to a variable
- you can copy it
- you can add attributes to it
- you can pass it as a function parameter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Creating classes dynamically
Since classes are objects, you can create them on the fly, like any object.
First, you can create a class in a function using class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
But it’s not so dynamic, since you still have to write the whole class yourself.
Since classes are objects, they must be generated by something.
When you use the class keyword, Python creates this object automatically. But as with most things in Python, it gives you a way to do it manually.
Remember the function type? The good old function that lets you know what type an object is:
1 2 3 4 5 6 7 8
Well, type has a completely different ability, it can also create classes on the fly. type can take the description of a class as parameters, and return a class.
(I know, it’s silly that the same function can have two completely different uses according to the parameters you pass to it. It’s an issue due to backwards compatibility in Python)
type works this way:
type(name of the class, tuple of the parent class (for inheritance, can be empty), dictionary containing attributes names and values) e.g.:
can be created manually this way:
1 2 3 4 5
You’ll notice that we use “MyShinyClass” as the name of the class and as the variable to hold the class reference. They can be different, but there is no reason to complicate things.
type accepts a dictionary to define the attributes of the class. So:
Can be translated to:
And used as a normal class:
1 2 3 4 5 6 7 8 9
And of course, you can inherit from it, so:
1 2 3 4 5
Eventually you’ll want to add methods to your class. Just define a function with the proper signature and assign it as an attribute.
1 2 3 4 5 6 7 8 9 10 11
You see where we are going: in Python, classes are objects, and you can create a class on the fly, dynamically.
This is what Python does when you use the keyword class, and it does so by using a metaclass.
What are metaclasses (finally)
Metaclasses are the ‘stuff’ that creates classes.
You define classes in order to create objects, right?
But we learned that Python classes are objects.
Well, metaclasses are what create these objects. They are the classes’ classes, you can picture them this way:
You’ve seen that type lets you do something like this:
It’s because the function type is in fact a metaclass. type is the metaclass Python uses to create all classes behind the scenes.
Now you wonder why the heck is it written in lowercase, and not Type?
Well, I guess it’s a matter of consistency with str, the class that creates strings objects, and int the class that creates integer objects. type is just the class that creates class objects.
You see that by checking the class attribute.
Everything, and I mean everything, is an object in Python. That includes ints, strings, functions and classes. All of them are objects. And all of them have been created from a class:
1 2 3 4 5 6 7 8 9 10 11 12 13
Now, what is the class of any class ?
1 2 3 4 5 6 7 8
So, a metaclass is just the stuff that creates class objects.
You can call it a ‘class factory’ if you wish.
type is the built-in metaclass Python uses, but of course, you can create your own metaclass.
The metaclass attribute
You can add a metaclass attribute when you write a class:
1 2 3
If you do so, Python will use the metaclass to create the class Foo.
Careful, it’s tricky.
You write class Foo(object) first, but the class object Foo is not created in memory yet.
Python will look for metaclass in the class definition. If it finds it, it will use it to create the object class Foo. If it doesn’t, it will use type to create the class.
Read that several times.
When you do:
Python does the following:
Is there a metaclass attribute in Foo?
If yes, create in memory a class object (I said a class object, stay with me here), with the name Foo by using what is in metaclass.
If Python can’t find metaclass, it will look for a metaclass in Bar (the parent class), and try to do the same.
If Python can’t find metaclass in any parent, it will look for a metaclass at the MODULE level, and try to do the same.
Then if it can’t find any metaclass at all, it will use type to create the class object.
Now the big question is, what can you put in metaclass ?
The answer is: something that can create a class.
And what can create a class? type, or anything that subclasses or uses it.
The main purpose of a metaclass is to change the class automatically, when it’s created.
You usually do this for APIs, where you want to create classes matching the current context.
Imagine a stupid example, where you decide that all classes in your module should have their attributes written in uppercase. There are several ways to do this, but one way is to set metaclass at the module level.
This way, all classes of this module will be created using this metaclass, and we just have to tell the metaclass to turn all attributes to uppercase.
Luckily, metaclass can actually be any callable, it doesn’t need to be a formal class (I know, something with ‘class’ in its name doesn’t need to be a class, go figure… but it’s helpful).
So we will start with a simple example, by using a function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
Now, let’s do exactly the same, but using a real class for a metaclass:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
But this is not really OOP. We call type directly and we don’t override call the parent new. Let’s do it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
You may have noticed the extra argument upperattr_metaclass. There is nothing special about it: a method always receives the current instance as first parameter. Just like you have self for ordinary methods.
Of course, the names I used here are long for the sake of clarity, but like for self, all the arguments have conventional names. So a real production metaclass would look like this:
1 2 3 4 5 6 7 8 9 10 11 12
We can make it even cleaner by using super, which will ease inheritance (because yes, you can have metaclasses, inheriting from metaclasses, inheriting from type):
1 2 3 4 5 6 7 8 9 10 11 12
That’s it. There is really nothing more about metaclasses.
The reason behind the complexity of the code using metaclasses is not because of metaclasses, it’s because you usually use metaclasses to do twisted stuff relying on introspection, manipulating inheritance, vars such as dict, etc.
Indeed, metaclasses are especially useful to do black magic, and therefore complicated stuff. But by themselves, they are simple:
- intercept a class creation
- modify the class
- return the modified class
Why would you use metaclasses classes instead of functions?
Since metaclass can accept any callable, why would you use a class since it’s obviously more complicated?
There are several reasons to do so:
- The intention is clear. When you read UpperAttrMetaclass(type), you know what’s going to follow
- You can use OOP. Metaclass can inherit from metaclass, override parent methods. Metaclasses can even use metaclasses.
- You can structure your code better. You never use metaclasses for something as trivial as the above example. It’s usually for something complicated. Having the ability to make several methods and group them in one class is very useful to make the code easier to read.
- You can hook on new, init and call. Which will allow you to do different stuff. Even if usually you can do it all in new, some people are just more comfortable using init.
- These are called metaclasses, damn it! It must mean something!
Why the hell would you use metaclasses?
Now the big question. Why would you use some obscure error prone feature?
Well, usually you don’t:
Metaclasses are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you don’t (the people who actually need them know with certainty that they need them, and don’t need an explanation about why).
Python Guru Tim Peters
The main use case for a metaclass is creating an API. A typical example of this is the Django ORM.
It allows you to define something like this:
1 2 3
But if you do this:
It won’t return an IntegerField object. It will return an int, and can even take it directly from the database.
This is possible because models.Model defines metaclass and it uses some magic that will turn the Person you just defined with simple statements into a complex hook to a database field.
Django makes something complex look simple by exposing a simple API and using metaclasses, recreating code from this API to do the real job behind the scenes.
The last word
First, you know that classes are objects that can create instances.
Well in fact, classes are themselves instances. Of metaclasses.
1 2 3
Everything is an object in Python, and they are all either instances of classes or instances of metaclasses.
Except for type.
type is actually its own metaclass. This is not something you could reproduce in pure Python, and is done by cheating a little bit at the implementation level.
Secondly, metaclasses are complicated. You may not want to use them for very simple class alterations. You can change classes by using two different techniques:
- monkey patching
- class decorators
99% of the time you need class alteration, you are better off using these.
But 99% of the time, you don’t need class alteration at all :-)