Sub topic 12
Choosing Between `__init_subclass__`, Decorators and Metaclasses
This chapter assumes you know how a class statement becomes a call to type, and that you have seen __init_subclass__, __set_name__, class decorators and a basic metaclass. Here you will compare them. The goal is a repeatable way to pick the lightest tool that solves a problem, and to recognize the problems that need a metaclass.
The short rule
Start with the weakest tool and move up only when you hit a concrete limit.
- Use a plain function or a class decorator when you only need to modify or register a class after it exists.
- Use
__init_subclass__when every subclass of a base class needs the same setup or validation. - Use
__set_name__when the object stored in a class attribute needs to know its own name. - Use a metaclass when you must change how the class is built or how it is called, or when the class object itself needs behavior.
What each tool can see and change
Each tool runs at a different moment and has a different reach.
| Tool | Runs when | Applies to | Can change |
|---|---|---|---|
| Class decorator | After the class is fully built | Only the class it decorates | The finished class, or return a different object |
| `__init_subclass__` | Inside `type.__new__`, after the class exists | Every subclass of the base, not the base itself | The new subclass (add attributes, validate, register) |
| `__set_name__` | Inside `type.__new__`, before `__init_subclass__` | One descriptor object per attribute | The descriptor itself |
| Metaclass `__prepare__` | Before the class body runs | Every class using the metaclass, including subclasses | The namespace mapping used by the body |
| Metaclass `__new__` | When the class is created | Same | The name, bases and namespace before the class exists |
| Metaclass `__call__` | When the class is called to make an instance | Same | Instance creation |
The order of events
When several hooks are present, they run in a fixed order. This script prints it.
class Meta(type):
def __new__(mcls, name, bases, namespace, **kwargs):
print('meta __new__ start')
cls = super().__new__(mcls, name, bases, namespace, **kwargs)
print('meta __new__ end')
return cls
def __init__(cls, name, bases, namespace, **kwargs):
super().__init__(name, bases, namespace, **kwargs)
print('meta __init__')
class Descr:
def __set_name__(self, owner, name):
print(f'__set_name__ {name}')
class Base(metaclass=Meta):
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
print('__init_subclass__')
def deco(cls):
print('decorator')
return cls
print('--- defining Child ---')
@deco
class Child(Base):
attr = Descr()The output after the marker line is:
meta __new__ start
__set_name__ attr
__init_subclass__
meta __new__ end
meta __init__
decorator__set_name__ and __init_subclass__ run inside the call to type.__new__. The decorator runs last. This has two consequences:
- A decorator sees the result of everything else, so it can fix up what the hooks did.
__init_subclass__runs before the metaclass__init__and before any decorator. Do not rely on state that either of those creates.
Task 1: registering classes
Registration is the most common reason people reach for a metaclass. All three tools can do it.
A decorator is the most explicit. The class opts in by name:
registry = {}
def register(cls):
registry[cls.__name__.lower()] = cls
return cls
@register
class Csv:
pass
class TsvCsv(Csv):
pass
print(sorted(registry)) # ['csv']TsvCsv is not registered, because a decorator applies only to the class it is written on. Sometimes that is what you want. When you want every subclass registered, the decorator is the wrong tool.
__init_subclass__ registers every subclass automatically:
class Plugin:
registry = {}
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
Plugin.registry[cls.__name__.lower()] = cls
class Csv(Plugin):
pass
class TsvCsv(Csv):
pass
print(sorted(Plugin.registry)) # ['csv', 'tsvcsv']A metaclass (RegistryMeta from the earlier chapter) gives the same result with more machinery. It also registers the base class itself, which __init_subclass__ does not. That difference is the only reason to prefer the metaclass here, and most registries do not want the base class in them.
Task 2: validating a class
Validation at class-definition time turns a runtime failure into an immediate one. __init_subclass__ is a good fit because it runs once per subclass, at the point of definition.
class Command:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
if not callable(getattr(cls, 'run', None)):
raise TypeError(f'{cls.__name__} must define run()')
class Good(Command):
def run(self):
pass
try:
class Bad(Command):
pass
except TypeError as exc:
print(exc) # Bad must define run()getattr also finds methods inherited from a parent, so a subclass of Good passes without redefining run. If you wanted to require that each class define its own run, check 'run' in cls.__dict__ instead.
If you only need to force subclasses to implement methods, abc.ABC with @abstractmethod already does this, at instantiation time instead of definition time. Use __init_subclass__ when you need the earlier failure or a custom rule that abc cannot express.
Task 3: attribute-level behavior
If the problem is "this attribute needs to know its name", use __set_name__ and nothing else. It needs no hook on the owning class, so it works with any class, including ones you do not control. Reaching for a metaclass that scans the namespace for Field objects was the standard pattern before Python 3.6. It is now unnecessary for naming.
A metaclass or __init_subclass__ is still useful when the class needs to collect these attributes, for example to build a list of all fields. A common pattern is to let __set_name__ do the per-field work and __init_subclass__ do the gathering:
class Field:
def __set_name__(self, owner, name):
self.name = name
class Model:
fields = ()
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
own = [k for k, v in vars(cls).items() if isinstance(v, Field)]
cls.fields = tuple(getattr(cls, 'fields', ())) + tuple(own)
class Base(Model):
id = Field()
class User(Base):
email = Field()
print(User.fields) # ('id', 'email')This example reads cls.fields before assigning it. Because cls.fields is looked up through inheritance, each subclass starts from its parent's tuple and extends it. A mutable list shared on the base class would be extended in place by every subclass, which is a common bug.
Task 4: modifying a class you do not own
A decorator is a plain function that takes a class and returns a class. You can apply it to a class from a library without subclassing, and you can call it as a function:
def add_repr(cls):
def __repr__(self):
items = ', '.join(f'{k}={v!r}' for k, v in vars(self).items())
return f'{cls.__name__}({items})'
cls.__repr__ = __repr__
return cls
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
Point = add_repr(Point)
print(Point(1, 2)) # Point(x=1, y=2)__init_subclass__ cannot do this, since it only fires for subclasses of a class you control. A metaclass cannot do it either, since the class already has a metaclass. Decorators also compose: stack as many as you like, with no conflict rules. The standard library's dataclasses.dataclass and functools.total_ordering are decorators for this reason.
When only a metaclass will do
Some jobs cannot be done from __init_subclass__ or a decorator.
Controlling instance creation. __init_subclass__ runs when the class is defined, not when it is called. To intercept Config() you must override __call__ on the metaclass, as in the singleton example. (For a singleton, a module-level instance or a factory function is often simpler.)
Changing the namespace while the body runs. __prepare__ is the only hook that runs before the class body. The duplicate-name check from the earlier chapter cannot be written any other way, because by the time any other hook runs, a duplicate has already overwritten the earlier value.
Changing the name, bases or namespace before the class exists. __init_subclass__ receives a finished class. A metaclass __new__ can add bases, rename the class or remove entries from the namespace first.
Giving the class itself behavior. Special methods are looked up on the type of an object. For an instance, that type is its class. For a class, that type is its metaclass. So to make a class iterable, you define __iter__ on the metaclass:
class MembersMeta(type):
def __iter__(cls):
return iter(cls._members)
def __len__(cls):
return len(cls._members)
class Color(metaclass=MembersMeta):
_members = ['red', 'green', 'blue']
print(list(Color)) # ['red', 'green', 'blue']
print(len(Color)) # 3This is how enum.Enum supports for color in Color and len(Color). Defining __iter__ as an ordinary method on Color would only make instances iterable.
Composition and conflicts
The strongest practical argument for __init_subclass__ is that it composes. A class has exactly one metaclass, and combining two bases with unrelated metaclasses raises a metaclass conflict. A hook on a base class has no such limit, because it is just an inherited method that cooperates through super().
from abc import ABC, abstractmethod
class Handler(ABC):
registry = {}
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
Handler.registry[cls.__name__] = cls
@abstractmethod
def handle(self):
...
class Echo(Handler):
def handle(self):
return 'echo'
print(sorted(Handler.registry)) # ['Echo']
print(Echo().handle()) # echoABC already uses the metaclass ABCMeta. A registry written as a second metaclass would force you to define a combined metaclass. The hook version needs nothing extra.
Note that abstract subclasses are registered too. If you want only concrete classes, check inspect.isabstract(cls) inside the hook.
Common mistakes
- Forgetting `super()._initsubclass__(kwargs)
.** Without it, a sibling mixin's hook never runs, and unused class keywords are silently swallowed instead of raisingTypeError`. - Expecting the hook to run on the base itself.
__init_subclass__fires for subclasses only. If the base needs setup, do it in the class body. - Using a decorator and expecting inheritance. The decorator ran once, on one class.
- Reading state too early. Inside
__init_subclass__, the class exists but a decorator has not yet run, so attributes the decorator adds are missing. - Reaching for a metaclass first. It makes the code harder to read, forces conflict handling on users who subclass your classes, and usually does something a hook could.
A checklist
Ask these questions in order and stop at the first yes.
- Is it a class you do not control, or should only some classes opt in? Use a decorator.
- Does an attribute need its own name? Use
__set_name__. - Should every subclass be registered, validated or configured? Use
__init_subclass__. - Do you need
__prepare__, to change bases or the namespace before creation, to intercept calls to the class, or to add special methods to the class object? Use a metaclass.
Exercise
A library gives you a class Report that you cannot edit. You want to add a to_json method to it, and also to any classes you define as subclasses of it. Which tool do you use for each part, and why?
Show answer
For Report itself, use a class decorator (or call a function on it) such as Report = add_to_json(Report), because __init_subclass__ only runs for subclasses and cannot touch a class you do not own. For your own subclasses, to_json is inherited from the decorated Report, so no further tool is needed. If you also want per-subclass setup, define a base class of your own that inherits from Report and uses __init_subclass__.
Exercise
You write class Registry(type) to register classes, then combine a class that uses it with a class that uses abc.ABCMeta as class C(A, B). What error do you get, and which tool would have avoided it?
Show answer
Python raises TypeError for a metaclass conflict, because neither Registry nor ABCMeta is a subclass of the other. Using __init_subclass__ on a plain base class for the registry avoids the conflict, since it does not add a metaclass. The alternative is a combined metaclass that inherits from both.
Exercise
Why can the class Color support len(Color) only if __len__ is defined on a metaclass and not as a normal method in the class body?
Show answer
Python looks up special methods on the type of the object. len(Color) looks on type(Color), which is the metaclass. A __len__ defined in the class body belongs to type(instance), so it makes len(Color()) work instead.