Sub topic 12
Choosing between `__init_subclass__`, decorators and metaclasses
This chapter assumes you can write classes with inheritance, call super(), use decorators, and pass **kwargs. It also assumes you have seen __init_subclass__, __set_name__ and a basic metaclass in earlier chapters. Here you will learn how to pick the lightest of the three tools for a given job.
The rule of thumb
All three tools run code when a class is created, but they differ in reach and cost.
- A class decorator runs once, on one class, after the class exists.
__init_subclass__runs on the parent each time someone subclasses it.- A metaclass takes part in the creation itself. It can change the namespace before the body runs, and it can change what happens when the class is called.
Start with the lightest tool and move up only when it cannot do the job.
Class decorators: one class at a time
Use a decorator when you opt in class by class. The decorator receives a finished class and returns it, usually after adding or wrapping attributes.
def add_repr(cls):
fields = list(cls.__annotations__)
def __repr__(self):
values = ", ".join(f"{n}={getattr(self, n)!r}" for n in fields)
return f"{cls.__name__}({values})"
cls.__repr__ = __repr__
return cls
@add_repr
class Point:
x: int
y: int
def __init__(self, x, y):
self.x = x
self.y = y
print(Point(1, 2)) # Point(1, 2)A decorator does not touch subclasses. If Point3D inherits from Point, it inherits the generated __repr__ but lists only x and y. Nothing re-runs the decorator for the subclass.
`__init_subclass__`: every subclass, automatically
Use __init_subclass__ when a base class needs to register or validate every subclass without the subclass author doing anything extra.
class Shape:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
if not callable(getattr(cls, "area", None)):
raise TypeError(f"{cls.__name__} must define area()")
class Square(Shape):
def area(self):
return 4
try:
class Broken(Shape):
pass
except TypeError as exc:
print(exc) # Broken must define area()The check runs at class definition time, so the error appears at import and not when the first instance is used. Always call super().__init_subclass__(**kwargs) so cooperative multiple inheritance keeps working.
Metaclasses: when the other two cannot reach
A metaclass is the right tool when you need something that happens before or around class creation. These are the usual cases:
- Controlling the class body with
__prepare__, for example to reject duplicate names. - Controlling instance creation with
__call__, as in theSingletonexample from earlier in this tutorial. - Changing the namespace before the class object exists, which a decorator or
__init_subclass__sees only afterward. - Customizing class-level behavior such as
len(MyClass)orMyClass[int]. These lookups go through the class's type, so the methods must live on the metaclass.
The cost is composability. Two libraries that each ship their own metaclass cannot be combined in one class until you write a third metaclass that inherits from both.
Comparing the three
| Concern | Class decorator | `__init_subclass__` | Metaclass |
|---|---|---|---|
| Applies to subclasses | No, apply it again | Yes, automatically | Yes, automatically |
| Runs | After the class is built | After the class is built | During creation |
| Can change the body namespace | No | No | Yes, with `__prepare__` |
| Can change what `Cls()` does | No | No | Yes, with `__call__` |
| Combines with other libraries | Easily | Easily | Can cause a metaclass conflict |
Common mistakes
- Using a metaclass to register subclasses.
__init_subclass__does this in a few lines and avoids conflicts. - Forgetting that a decorator is not inherited, then expecting subclasses to be processed.
- Skipping
super().__init_subclass__(**kwargs), which breaks other classes in the inheritance chain. - Doing heavy work in a hook that runs at import time. Keep these hooks cheap and deterministic.
Exercise
You are building a plugin framework. Every plugin class must be added to a registry as soon as it is defined, and plugin authors should only write class MyPlugin(Plugin):. Which tool do you choose, and why not a class decorator?
Show answer
Use __init_subclass__ on the Plugin base class and add cls to the registry there. A class decorator would force each plugin author to remember to apply it, and it would not run for subclasses of plugins. A metaclass would also work, but it is heavier and can conflict with other metaclasses.
Exercise
A class needs to return the same instance every time it is called. Can __init_subclass__ or a class decorator do this? Which tool can?
Show answer
Neither can, because both run after the class is built and do not change what happens when the class is called. A metaclass that overrides __call__ can. A decorator could replace the class with a wrapper, but that changes what the name refers to, so it is not equivalent.