Magic.
No really.
Python classes are not a composite structure like in C ++. They themselves, just objects, are instances of another type:
class Foo(object): pass print(type(Foo))
You can even make a class as if you made any other object by calling type . It:
class Bar(object): a = 1 b = 2
Actually (more or less) syntactic sugar for this:
Bar = type('Bar', (object,), {'a': 1, 'b': 2})
type takes the name of your new class, a list of its superclasses and a specification of all the attributes of the class and splashes out the new class.
But since type is just a class like any other, you can subclass it and give it a different behavior. And this is what Django did: he created a subclass of type that does something else with the attribute attribute that you pass to it.
You do not see this happening directly in your own code, but if you check type(models.Model) , you will find out that its type is not type , but something special for Django. He probably has a βmetaβ in the name because he called the metaclass: class of the class.
This is a fairly common template for creating "declarative" libraries in Python, where class attributes actually define some structure. You can see the same thing in form validation (wtforms), schema validation (colander), other ORMs (sqlalchemy), and even the stdlib enumeration module.
source share