Every Python developer knows that everything is an object. What fewer know is that classes are objects too, and like every other object, they are instances of something. That something is a metaclass. Understanding metaclasses means understanding how Python builds classes in the first place, which turns out to explain a lot of behavior that otherwise looks like magic.
Classes Are Instances of type
Start here:
class MyClass : pass
print ( type ( MyClass )) # <class 'type'> print ( type ( int )) # <class 'type'> print ( type ( str )) # <class 'type'> print ( type ( type )) # <class 'type'>
Enter fullscreen mode
Exit fullscreen mode
type is the metaclass of every class you have ever written unless you said otherwise. It is the class of classes. It is also an instance of itself, which is one of those things that is true and also slightly uncomfortable to think about for too long.
Since type is a class, you can call it to create new classes at runtime.…