Metaclasses
A metaclass is the class of a class. It decides how a class object is created from a class statement. The default metaclass is type. You write one only when you must change that process.
Detailed Explanation
class Order: is a call to a metaclass. Python collects the class name, the bases, and the namespace of the body, then calls Meta(name, bases, namespace). The return value is the class object. type is the metaclass that does the normal thing. type(Order) is type for ordinary classes.
Because classes are objects, they have a type. That type can have methods. Those methods are the class-level hooks: __new__ and __init__ on the metaclass receive the not-yet-finished or just-finished class. __prepare__ can supply a custom mapping for the class body (for example, to remember definition order, which type already does in modern Python).
People reach for a metaclass to register subclasses automatically, to rewrite methods, to enforce an API, or to implement an ORM. Most of those jobs now have a lighter hook. __init_subclass__ runs on a base when a subclass is created; it is enough for registries. __set_name__ handles descriptor naming. Class decorators wrap the finished class. Use a metaclass last.
When two bases have different metaclasses, Python tries to find a common subclass of those metaclasses. If it cannot, you get TypeError: metaclass conflict. This is why libraries that each want to be "the" metaclass do not compose. Prefer __init_subclass__ on each base so they can coexist.
ABCMeta is the metaclass behind abc.ABC. Enums use a metaclass. You already depend on metaclasses; you rarely need to write one.
Debugging a metaclass means printing in Meta.__new__ and checking type(cls). If you do not know why a class looks wrong, check for a metaclass before you blame inheritance.
Code Examples
class Plugin(type):
registry: dict[str, type] = {}
def __new__(mcls, name, bases, namespace):
cls = super().__new__(mcls, name, bases, namespace)
if name != "Base":
mcls.registry[name] = cls
return cls
class Base(metaclass=Plugin):
pass
class Stripe(Base):
pass
print(Plugin.registry) # {'Stripe': <class 'Stripe'>}
print(type(Stripe) is Plugin) # True# The lighter replacement for many registries:
class Handler:
kinds: dict[str, type] = {}
def __init_subclass__(cls, *, kind: str, **kwargs):
super().__init_subclass__(**kwargs)
cls.kinds[kind] = cls
class Email(Handler, kind="email"):
pass
print(Handler.kinds) # {'email': <class 'Email'>}Common Gotchas
Metaclass conflicts
two libraries, two metaclasses, one class body. You cannot fix this at the call site. Redesign with `__init_subclass__`.
A metaclass `__new__` that forgets `super().__new__`
you skip slots, annotations, and other machinery. Always build the class through `super`.
Class decorators run after the metaclass
registration that must see the raw namespace belongs in the metaclass or `__init_subclass__`, not in a decorator that never ran.
`type("Order", (), {})` is a metaclass call
it is the dynamic form of `class Order: pass`.