Sub topic 4
Hooking subclass creation with `__init_subclass__`
This chapter assumes you can define classes and inheritance hierarchies, call super() in methods, and use **kwargs. It also assumes you know that a class is an object and that type(name, bases, namespace) builds one. You don't need to know metaclasses yet. __init_subclass__ exists so that many jobs people once gave to metaclasses can be done without one.
What the hook is
__init_subclass__ is a method you define on a parent class. Python calls it every time a new subclass of that parent is created. It lets a base class react to being inherited from. It can register the subclass, check it, or fill in defaults.
Three facts define its behavior:
- It is an implicit class method. You write
def __init_subclass__(cls, ...)without@classmethod, and Python wraps it for you. Adding@classmethodyourself also works. clsis the new subclass, not the class that defines the hook.- It is called on the parent, so it never runs for the class that defines it. It runs for each class that inherits from it, directly or indirectly.
The default implementation lives on object and does nothing. That is why every subclass can safely call super().__init_subclass__().
A registry without a metaclass
The classic use is a plugin registry. This example comes from the plan for this tutorial.
class Plugin:
registry = {}
def __init_subclass__(cls, /, name=None, **kwargs):
super().__init_subclass__(**kwargs)
Plugin.registry[name or cls.__name__.lower()] = cls
class CsvPlugin(Plugin, name='csv'):
pass
class JsonPlugin(Plugin):
pass
print(sorted(Plugin.registry)) # ['csv', 'jsonplugin']Three things happen here.
Pluginitself is not in the registry, because the hook only fires for subclasses.CsvPluginpassesname='csv'in the class line. Python forwards that keyword argument to__init_subclass__. The next chapter covers class keyword arguments in detail, so here it is enough to see that the hook receives them.- The hook writes to
Plugin.registryrather thancls.registry = .... Assigning throughclswould create a new attribute on each subclass and shadow the shared dictionary. Mutating the dictionary through the parent keeps one registry.
Grandchildren register too. If class FancyCsv(CsvPlugin) is defined later, the hook runs again with cls set to FancyCsv. It runs because FancyCsv inherits the hook through CsvPlugin.
The hook also fires for classes built with type():
class Plugin:
registry = {}
def __init_subclass__(cls, /, **kwargs):
super().__init_subclass__(**kwargs)
Plugin.registry[cls.__name__] = cls
Dynamic = type('Dynamic', (Plugin,), {})
print(sorted(Plugin.registry)) # ['Dynamic']This is expected. A class statement ends in a call to type (or a metaclass), and that call is where the hook is triggered.
When it runs
The hook runs inside type.__new__, after the class object exists and its body has been executed. This ordering matters.
You can see this order directly:
class Base:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
print('init_subclass', cls.__name__, 'x' in cls.__dict__)
def deco(c):
print('decorator', c.__name__)
return c
@deco
class Child(Base):
x = 1The output is:
init_subclass Child True
decorator ChildTwo consequences follow:
- The hook can read everything the class body defined, through
cls.__dict__orgetattr(cls, ...). Inherited attributes are visible as well. - The hook cannot see changes that a class decorator makes later, and it cannot see attributes you assign after the class statement finishes.
Validating subclasses
Because the hook runs at class definition time, it can reject a bad subclass before any instance exists. An exception raised inside it propagates out of the class statement, and the class name is never bound.
class Handler:
required = ('handle',)
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
missing = [n for n in cls.required if not callable(getattr(cls, n, None))]
if missing:
raise TypeError(f"{cls.__name__} must define: {', '.join(missing)}")
class Good(Handler):
def handle(self):
return 'ok'
try:
class Bad(Handler):
pass
except TypeError as exc:
print(exc) # Bad must define: handle
print('Good' in globals(), 'Bad' in globals()) # True FalseThis is stricter than abc.abstractmethod. Abstract methods are checked when you try to create an instance. This hook checks when the class is defined, so the error points at the class statement that caused it.
The check applies to every subclass, including intermediate ones. If you want an abstract middle layer that is allowed to skip the check, you need an explicit marker. A common choice is to test cls.__dict__.get('abstract', False). Use cls.__dict__ rather than getattr, because getattr would find the flag inherited from the parent and skip every descendant of the abstract class too.
Cooperating with other classes
In multiple inheritance, several parents can each define __init_subclass__. Python looks the hook up through the new class's method resolution order (MRO). It calls the first one it finds. That hook must call super().__init_subclass__(**kwargs) so the rest of the chain runs.
class Tracked:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
print(f'Tracked saw {cls.__name__}')
class Audited:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
print(f'Audited saw {cls.__name__}')
class Model(Tracked, Audited):
passThe MRO of Model is Model, Tracked, Audited, object. The call chain goes down to Audited, then object, and the prints happen on the way back. The output is:
Audited saw Model
Tracked saw ModelIf Tracked forgot the super() call, Audited would never run for Model, and nothing would warn you. Always call super().__init_subclass__(**kwargs), even when your class has no parents that define the hook.
Forwarding keyword arguments
The signature convention is def __init_subclass__(cls, /, own_option=None, **kwargs). The hook takes the options it understands, then passes the rest up the chain. This matters because the final stop is object.__init_subclass__, which accepts no keyword arguments. If you write class Oops(Base, flavour='x') and no hook consumes flavour, you get a TypeError. That is the correct outcome, since it catches typos in the class line.
Avoid swallowing unknown keywords with a bare **kwargs and no forwarding. Doing so hides mistakes and breaks any cooperating parent that expected its own options.
What the hook does not do
The table summarizes when the hook fires.
| Situation | Does `__init_subclass__` run? |
|---|---|
| `class Child(Parent):` where `Parent` defines the hook | Yes, with `cls=Child` |
| `class GrandChild(Child):` | Yes, through inheritance |
| The `class Parent:` statement that defines the hook | No |
| `type('Dyn', (Parent,), {})` | Yes |
| Changing `Child.__bases__` or adding attributes later | No |
| Creating an instance of `Child` | No |
Several limits are worth knowing:
- It only sees subclasses. A hook on
Parentcannot observe classes that don't inherit fromParent. If you need to alter the class being defined by name, or intercept the class body, you need a different tool. - It cannot change what the class statement evaluates to. The returned value is ignored, and the class that
type.__new__built is the class you get. A class decorator or a metaclass can return a different object. - It cannot change the namespace before the class is created. The namespace has already been turned into the class by the time the hook runs. You can still set attributes on
cls, for examplecls.table_name = cls.__name__.lower(), but you cannot rename or remove entries from the original body mapping. - It cannot customize instance creation. Calling
Child()does not involve the hook. Overriding__call__on a metaclass handles that, and a later chapter covers it.
Common mistakes
- Forgetting `super()._initsubclass__(kwargs)`.** Cooperating hooks further down the MRO silently stop running.
- Assigning shared state through
cls.cls.registry = {}makes a fresh dictionary per subclass. Mutate the shared object, or create it once on the base class. - Registering abstract intermediates. A base such as
class Handlerthat is only meant for inheritance may need an explicit marker so it skips registration or validation. - Relying on decorated state. The hook runs before class decorators. If a decorator adds a method, the hook will not see it.
- Doing heavy work at import time. The hook runs while modules import. A slow or failing hook breaks the import of every module that defines a subclass.
- Name collisions in registries. Two subclasses with the same lowercased name overwrite each other. Decide whether to raise an error on a duplicate:
class Plugin:
registry = {}
def __init_subclass__(cls, /, name=None, **kwargs):
super().__init_subclass__(**kwargs)
key = name or cls.__name__.lower()
if key in Plugin.registry:
raise ValueError(f'duplicate plugin name: {key}')
Plugin.registry[key] = clsWhy not a metaclass?
A metaclass can do everything shown here, since it controls the class creation call itself. The hook is the lighter option for three reasons:
- It needs no change to how the class is built, so it does not add a metaclass to the inheritance graph. Unrelated metaclasses cannot be combined without a merging subclass, a problem a later chapter covers.
- It reads as an ordinary method on the base class, which most readers recognize without learning a new concept.
- It composes through
super(), the same way other cooperative methods do.
When the hook is not enough, a later chapter on choosing between the tools gives criteria for deciding.
Exercise
Write a base class Shape with an _initsubclass_ hook that requires every subclass to define an integer class attribute sides of at least 3. The hook should raise TypeError with the class name in the message if the attribute is missing or invalid, and it should call super().initsubclass_(**kwargs). Why does the check have to use getattr(cls, 'sides', None) instead of `cls.dict_`, and what is the downside of that choice?
Show answer
Define def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs); sides = getattr(cls, 'sides', None); if not isinstance(sides, int) or sides < 3: raise TypeError(f'{cls.__name__} needs an integer sides >= 3'). Using getattr lets a subclass such as class Square(Rectangle) pass by inheriting sides from its parent, whereas cls.__dict__ would force every class to repeat the attribute. The downside is that a subclass can no longer be forced to declare its own value, so a forgotten override is silently inherited from the parent.