Prerequisites
- !Classes are instances of type
- !Decorators, class bodies, and attribute lookup
What You'll Learn
- 1Describe class creation as two steps with distinct responsibilities
- 2Transform attributes safely inside a metaclass __new__
- 3Use __init_subclass__ for registration and validation
- 4Recognise when a framework's metaclass will conflict with yours
- 5Walk down the simpler alternatives before writing a metaclass
Metaclasses have a reputation for advanced magic, and the reputation is partly earned. Underneath, a metaclass is just the class of a class: the same object, attribute, method machinery you already know, applied one level up. That framing turns an exotic topic into an ordinary one, and it also makes the warning clear. Because a metaclass controls creation of every class that inherits it, one metaclass in a hierarchy means a conflict when a second framework wants to own class creation too.
Class creation in two steps
When Python executes a class statement, it collects the namespace, resolves the bases, and asks the metaclass to build the object. The metaclass's __new__ creates and returns the class object; its __init__ then initialises the already-created object. The first is where transformations belong, because the attribute dictionary is still being assembled; the second is where bookkeeping such as registration belongs.
| Hook | Receives | Responsibility | Typical use |
|---|---|---|---|
Metaclass __new__ | name, bases, namespace | Create and return the class | Rewrite attributes, inject fields |
Metaclass __init__ | the new class | Register or annotate it | Registries, schema collection |
__init_subclass__ | the subclass | React to a derived class | Plugins, validation of definitions |
| Class decorator | the finished class | Wrap or patch after creation | One-off registration |
The important constraint on __new__ is that it must return an instance of its own class, and that any attribute rewriting has to happen before the class object exists, since later changes are ordinary attribute assignment and do not participate in creation. Keeping the two phases separate prevents the class of bug where a transformation runs twice or not at all depending on the Python version.
Transforming a class at creation
A metaclass that renames or wraps methods runs while the namespace is still a plain dictionary, which makes the work straightforward. The example below tags every public method with a marker so a framework can discover them later.
class Instrumented(type):
def __new__(mcls, name, bases, namespace, **kwargs):
instrumented = {}
for key, value in namespace.items():
if callable(value) and not key.startswith("_"):
value.__instrumented__ = True
instrumented[key] = value
cls = super().__new__(mcls, name, bases, instrumented, **kwargs)
cls.__registry__ = [c for c in bases if hasattr(c, "__registry__")]
cls.__registry__.append(cls)
return cls
class Service(metaclass=Instrumented):
def run(self):
return "running"
class Job(Service):
def execute(self):
return "executed"
print(Job.__registry__) # [Service, Job]
print(Job.execute.__instrumented__) # True
print(hasattr(Job, "run")) # True
Notice that inherited methods are not re-marked, because they are absent from the fresh namespace and only reachable through the bases, which is exactly the semantics you want: the marker describes where a method was defined. Also note __registry__ construction, which avoids aliasing the parent's list by copying rather than appending to it, a subtle error that silently pollutes every class in the hierarchy.
init_subclass: the tool that covers most needs
Before __init_subclass__, registration required a metaclass even though nothing about class creation needed changing. Now a base class can react to every subclass with no extra machinery, which removes the single most common reason to reach for a metaclass.
class Plugin:
plugins = {}
def __init_subclass__(cls, kind=None, **kwargs):
super().__init_subclass__(**kwargs)
cls.kind = kind or cls.__name__.lower()
if cls.kind in Plugin.plugins:
raise TypeError(f"duplicate plugin kind: {cls.kind}")
Plugin.plugins[cls.kind] = cls
@classmethod
def create(cls, kind):
try:
plugin_cls = Plugin.plugins[kind]
except KeyError:
raise ValueError(f"unknown plugin kind: {kind}") from None
return plugin_cls()
class CsvExporter(Plugin, kind="csv"):
def export(self):
return "csv output"
class JsonExporter(Plugin, kind="json"):
def export(self):
return "json output"
print(sorted(Plugin.plugins)) # ['csv', 'json']
print(Plugin.create("csv").export()) # csv output
The keyword argument in the class statement, kind="csv", is passed straight to __init_subclass__, which gives each subclass a way to declare metadata without writing an __init__. Duplicate detection at class creation time means a copy-paste error fails at import rather than at dispatch. The one thing __init_subclass__ cannot do is change how the class object is built, because the class already exists by then; for rewriting, you still need __new__ in a metaclass or a class decorator.
Validation at class creation
Metaclasses also shine when a class must satisfy a structural rule before any instance exists: required attributes with correct types, an interface fully implemented, or a schema consistent across the hierarchy. Failing at class creation puts the error at the import line, which is where a developer is looking.
class Validated(type):
def __new__(mcls, name, bases, namespace, **kwargs):
cls = super().__new__(mcls, name, bases, namespace, **kwargs)
if any(base.__name__ == "BaseModel" for base in bases):
fields = {k: v for k, v in vars(cls).items() if not k.startswith("_")}
if not fields:
raise TypeError(f"{name} must declare at least one field")
for field_name, annotation in fields.items():
if not isinstance(annotation, type):
raise TypeError(f"{name}.{field_name} must be a class annotation")
return cls
class BaseModel:
pass
class User(BaseModel):
name = str
age = int
print(vars(User)["name"]) # <class 'str'>
The guard checks only classes that actually inherit the marker, which keeps the metaclass reusable in a larger hierarchy. Escaping the angle brackets in the expected output matters in prose, but inside a code fence the comparison symbols are ordinary characters, which is a useful reminder that MDX parsing rules and Python syntax are separate concerns. When validation grows complex enough to need its own tests, move the logic into a module-level function and have the metaclass call it, keeping the metaclass itself a thin shell.
When two metaclasses collide
The practical limit of metaclasses is that a class cannot inherit from bases with incompatible metaclasses, and Python will refuse to create it with a conflict error. Frameworks such as ORMs and data-modelling libraries routinely define their own, so application code that also defines one tends to break when it meets them. This is not a design flaw in your code so much as a sign that two libraries both want to own class creation.
The escape routes are worth knowing in order. First, try a class decorator, which runs once after creation and can patch attributes without owning the type. Second, try __init_subclass__, which reacts to subclasses without interfering with construction. Third, use explicit registration calls or entry points instead of implicit discovery. Only if none of those can express the rule do you need a metaclass, and then prefer cooperating through super() calls so another metaclass can join the chain.
The alternatives ladder
Before writing a metaclass, walk this list. Each rung solves a real problem with far less coupling than the rung below it.
| Need | Simplest sufficient tool |
|---|---|
| Run code once when a class is defined | Class decorator |
| React to every subclass | __init_subclass__ |
| Validate or normalise a finished class | Class decorator calling a helper |
| Register a class in a plugin map | Decorator or explicit registration |
| Rewrite attributes during creation | Metaclass __new__ |
| Coordinate with a framework that has its own metaclass | Avoid; use composition instead |
The ladder is also a maintenance argument. A metaclass imposes itself on every subclass and every reader, while a decorator touches exactly the classes it decorates. When a colleague meets your code six months later, the decorator says what happened at this one point, and the metaclass asks them to understand the whole hierarchy first.
Debugging class creation
When class creation misbehaves, inspect rather than guess. Print type(cls) to see which metaclass is actually in effect, and use __mro__ to check whether your class or the framework's won. If attributes are missing, dump the namespace inside __new__ before and after transformation to see what the class statement produced. If an error mentions conflicting metaclasses, print type(base) for every base, since the conflict is almost always between two libraries rather than in your own code.
Keep metaclasses small, push logic into plain functions you can unit test directly, and document the contract that subclasses must satisfy. A metaclass that does one obvious thing to a namespace is maintainable; one that contains a framework is a maintenance burden nobody asked for.
Common Mistakes
Writing a metaclass when a class decorator would do
Fix: Walk the alternatives ladder; use a metaclass only when creation itself must change.
Appending to an inherited registry list instead of copying it
Fix: Build a fresh list from the bases so every class does not share and corrupt one list.
Defining a metaclass that conflicts with a framework's own
Fix: Compose with the framework's hooks, or use __init_subclass__ and decorators on your side.
Putting testable business logic inside a metaclass __new__
Fix: Extract the logic into module-level functions and keep the metaclass as a thin shell.
Best Practices
- Prefer __init_subclass__ for registration because it needs no extra type
- Copy inherited mutable class state rather than mutating it in place
- Keep class-creation validation at the import boundary where errors are visible
- Call super() in every metaclass hook so cooperating metaclasses can compose
- Document the attributes your metaclass injects so subclasses can rely on them
Key Takeaways
- A metaclass is the class of a class, built in a __new__ step followed by __init__
- __init_subclass__ handles registration and validation without owning class creation
- Class decorators cover one-off wrapping with far less coupling
- Two frameworks with different metaclasses cannot both own the same hierarchy
- Logic inside a metaclass should be extracted into functions that are testable alone