How __init_subclass__ Behaves: Timing, Keywords and Registries
This article explains when Python calls __init_subclass__ and for which classes, how class keywords reach it, how registries exclude abstract classes, and which mistakes break the hook.
Since Python 3.6, PEP 487 allows a class to react to the creation of its subclasses through the method __init_subclass__, a hook that covers most of the uses for which a metaclass was previously required. The present article does not return to the comparison with metaclasses or to the basic registration of plug-ins, already treated in the article devoted to metaclasses; it examines how the hook itself behaves. It establishes when the hook runs and for which classes, in what order it runs relative to __set_name__, how keyword arguments in a class statement reach it, how abstract intermediate classes are excluded from a registry, and which errors appear when a registry or an argument is handled carelessly. Executing the rules of a base class at the moment each subclass is written, rather than when it is first used, is the secret weapon of __init_subclass__.
Spawn Trigger: When and for Which Classes the Hook Runs
The hook runs once for each class that is created with the defining class among its ancestors, immediately after the new class object exists and before the class statement finishes. It is an implicit class method: Python converts it to a classmethod even without the decorator, so its first argument, cls, is the new subclass, not the class that defines the hook.
order = []
class Field:
def __set_name__(self, owner, name):
order.append(f"__set_name__ {name}")
class Base:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
order.append(f"__init_subclass__ {cls.__name__}")
class Child(Base):
size = Field()
class Grandchild(Child):
pass
print(order)
# Output: ['__set_name__ size', '__init_subclass__ Child', '__init_subclass__ Grandchild']
print(type(Base.__dict__["__init_subclass__"]).__name__) # Output: classmethod
Three facts follow from the output. The hook does not run for Base itself, only for classes derived from it. It runs for Grandchild as well, although Grandchild inherits from Child and not directly from Base, so a rule placed in a base class applies to its whole hierarchy. Finally, __set_name__, the other hook introduced by PEP 487, has already been called on every descriptor of the class body when __init_subclass__ runs, which means that the hook can inspect fields that already know their names.
Keyword Arguments in the Class Statement
The parentheses of a class statement accept keyword arguments in addition to the bases. Every keyword other than metaclass is passed to __init_subclass__, which may declare it as a keyword-only parameter with or without a default value.
class Task:
def __init_subclass__(cls, *, priority="low", **kwargs):
super().__init_subclass__(**kwargs)
cls.priority = priority
class UrgentTask(Task, priority="high"):
pass
class RoutineTask(Task):
pass
print(UrgentTask.priority, RoutineTask.priority) # Output: high low
try:
class Misspelled(Task, priorty="high"):
pass
except TypeError as error:
print(error) # Output (CPython 3.12): Misspelled.__init_subclass__() takes no keyword arguments
The hook takes the keyword that it understands and passes the remaining ones to super().__init_subclass__, so that other bases in a multiple inheritance hierarchy can take theirs, the cooperative convention examined in the article devoted to super(). A misspelled keyword travels along the chain until it reaches object.__init_subclass__, which accepts none, so the error appears at the moment the class is defined and not when it is used.
Registries and Abstract Intermediate Classes
A registry of subclasses usually needs to exclude classes that exist only to be extended, and to store its entries in a single, predictable place. A keyword argument marks the intermediate classes, and an explicit reference to the base class selects the registry.
class Plugin:
registry = {}
def __init_subclass__(cls, *, abstract=False, **kwargs):
super().__init_subclass__(**kwargs)
if not abstract:
Plugin.registry[cls.__name__.lower()] = cls
class Exporter(Plugin, abstract=True):
def export(self, rows):
raise NotImplementedError
class CsvExporter(Exporter):
def export(self, rows):
return "\n".join(",".join(map(str, row)) for row in rows)
class JsonExporter(Exporter):
pass
print(sorted(Plugin.registry)) # Output: ['csvexporter', 'jsonexporter']
print(Plugin.registry["csvexporter"]().export([(1, 2), (3, 4)]))
# Output: 1,2
# Output: 3,4
The intermediate class Exporter is not registered, while both concrete exporters are, because the keyword abstract is not inherited: each class statement passes its own keywords. The same hook can validate a subclass at definition time, for instance by requiring that it override export, which would reject JsonExporter as soon as its module is imported; the use of such registries to create objects by name is examined in the article devoted to the Factory pattern.
Pitfalls of __init_subclass__
The hook runs during class creation, when the class is not yet fully in use, so its errors tend to concern scope and timing rather than logic. Six pitfalls are distinguished, which are the following:
cls.registryinstead ofBase.registry. Writing throughclsreaches the base's container only while no subclass defines an attribute with the same name.- Forgetting
super().__init_subclass__(**kwargs). Another base in a multiple inheritance hierarchy then never receives its call or its keywords. - Unconsumed keywords. A keyword that no hook takes reaches
object.__init_subclass__and raisesTypeError. - Expecting the hook to run for the base. The class that defines the hook is not passed to it; any setup of the base itself belongs in its body.
- Registration depends on import. A subclass in a module that is never imported is never registered.
- Heavy work at definition time. Expensive operations in the hook slow down the import of every module that defines a subclass.
The first pitfall is reproduced in the following example.
class Base:
registry = []
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
cls.registry.append(cls.__name__)
class Middle(Base):
registry = []
class Leaf(Middle):
pass
print(Base.registry, Middle.registry) # Output: [] ['Middle', 'Leaf']
The class Middle defines its own registry, so when the hook runs for Middle and for Leaf, the expression cls.registry resolves to the new list and the base's registry remains empty. Referring to Base.registry explicitly, as in the previous section, avoids the problem; a separate registry per subclass, when it is wanted, should be created deliberately inside the hook.
Choosing a Class Customization Hook
Consequently, the hook is appropriate when a rule must apply to every subclass of a base, while other tools fit narrower or broader cases, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| Register or validate every subclass of a base | __init_subclass__ |
| Configure a subclass with values given in its class statement | Keyword arguments to __init_subclass__ |
| Modify one specific class only | A class decorator |
| An attribute must know its own name | __set_name__ on a descriptor |
| Require that subclasses implement methods before instantiation | abc.ABC and @abstractmethod |
| Change how the class object itself is built or its namespace | A metaclass |
Conclusion
It is concluded that __init_subclass__ is an implicit class method that the parent calls for every class derived from it, directly or indirectly, after the descriptors of the new class have received their names through __set_name__, and that keyword arguments in the class statement give each subclass a declarative configuration. This magic depends on cooperative calls to super(), on explicit references to the registry that must receive the classes, and on keywords that some hook actually consumes. Selecting the operation to perform according to the class of each object in a structure, without adding that operation to the classes themselves, is the purpose of the Visitor pattern, which is developed in a future article of this series.