Skip to main content
Albero Academy

Metaclasses

Classes that create classes — the deepest layer of Python objects.

Advanced Python9 min

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

the turtles-all-the-way-down
class Dog: ...
type(Dog) # <class 'type'> — Dog is an instance of type
type(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:

a metaclass
class Meta(type):
def __new__(mcls, name, bases, ns):
ns["created_by"] = "Meta" # inject an attribute
return super().__new__(mcls, name, bases, ns)
class Thing(metaclass=Meta):
pass
Thing.created_by # 'Meta' — added at class-creation time

Key takeaways

  1. 01A metaclass is the class of a class; the default is type.
  2. 02Classes are objects — type(SomeClass) is type; type() can even build classes dynamically.
  3. 03A metaclass customises class creation (registration, injection, enforcement).
  4. 04Frameworks use them; application code rarely needs them.
  5. 05Prefer class decorators or __init_subclass__ before reaching for a metaclass.

Finished this chapter?

Mark it complete to track your progress through Python.