A metaclass is the class of a class. In Python, everything is an object — including classes themselves. Just as an instance is created from a class, a class is created from a metaclass (the default being type). A metaclass lets you customise class creation.
Classes are instances of type
class Dog: ...type(Dog) # <class 'type'> — Dog is an instance of typetype(Dog()) # <class 'Dog'> — the instance is of Dog# You can even create a class dynamically with type():Cat = type("Cat", (), {"legs": 4})Cat().legs # 4
Customising class creation
A custom metaclass hooks into the moment a class is defined — to register it, inject attributes, or enforce rules:
class Meta(type):def __new__(mcls, name, bases, ns):ns["created_by"] = "Meta" # inject an attributereturn super().__new__(mcls, name, bases, ns)class Thing(metaclass=Meta):passThing.created_by # 'Meta' — added at class-creation time
Key takeaways
- 01A metaclass is the class of a class; the default is type.
- 02Classes are objects — type(SomeClass) is type; type() can even build classes dynamically.
- 03A metaclass customises class creation (registration, injection, enforcement).
- 04Frameworks use them; application code rarely needs them.
- 05Prefer class decorators or __init_subclass__ before reaching for a metaclass.
