Sub topic 4
Hooking subclass creation with `__init_subclass__`
This chapter assumes you can define classes and inheritance, call super(), and use **kwargs. You do not need to know metaclasses yet.
The problem
Suppose a base class must know about every subclass. It might keep a registry of plugins, or it might check that each subclass defines a required method. Before Python 3.6 this needed a metaclass or a decorator on every subclass. Now a base class can define __init_subclass__, and Python calls it each time a subclass is created.
A registry in a few lines
class Plugin:
registry = {}
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
Plugin.registry[cls.__name__.lower()] = cls
class CsvPlugin(Plugin):
pass
class JsonPlugin(Plugin):
pass
print(sorted(Plugin.registry)) # ['csvplugin', 'jsonplugin']__init_subclass__ is an implicit class method, so you do not need @classmethod. The cls argument is the new subclass, not Plugin. Defining CsvPlugin triggers the hook on Plugin, and cls is CsvPlugin.
Where the hook runs
When the hook runs, the class body has already finished. The class object exists and all its attributes are in place, so the hook can inspect them. The name is not bound yet, though. A class decorator, if there is one, runs after all of this.
Validating subclasses
The hook can also reject bad subclasses at definition time. This is earlier than an error at call time, and clearer than an AttributeError far from the cause.
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 __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
try:
class Broken(Shape):
pass
except TypeError as exc:
print(exc) # Broken must define area()The TypeError is raised by the class Broken statement itself, so the name Broken is never bound.
Details that cause bugs
- The parent is not hooked.
__init_subclass__runs only for subclasses.PluginandShapethemselves never trigger it. - Indirect subclasses are hooked too. If
CsvPlugingets a subclass, the hook runs again, still withPlugin's method (unlessCsvPluginoverrides it). - Always call `super()._initsubclass__(kwargs)
.** In a hierarchy with several bases, each hook must pass control along. If you skip the call, other hooks in the method resolution order never run. If you swallow**kwargs, a misspelled class keyword is silently ignored. Forwarding it letsobject._initsubclass__raise aTypeError`. - Hooks see the final class. Attributes that a subclass adds after the class statement, such as
Child.area = ..., are invisible to the hook. - Abstract checks are not the same as
abc. TheShapecheck above runs at class creation, but it only looks for an attribute.abc.ABCinstead blocks instantiation of classes with unimplemented abstract methods. Pick the one that matches when you want the error.
What this hook cannot do
__init_subclass__ runs after the class is built. You cannot use it to change the class body's namespace before creation, replace the class with a different object, or change what happens when the class is called. Those jobs need a metaclass, which comes later in this tutorial.
Exercise
Write a base class Command whose __init_subclass__ stores every subclass in a dict called commands, keyed by the subclass's name class attribute. Raise a TypeError if the subclass has no name attribute of its own type str. What happens to a subclass of a subclass that does not redefine name?
Show answer
Use name = getattr(cls, 'name', None); if not isinstance(name, str), raise TypeError(f'{cls.__name__} needs a str name'); otherwise set Command.commands[name] = cls; call super().__init_subclass__(**kwargs) first. A sub-subclass that does not redefine name inherits its parent's name through normal attribute lookup, so the check passes. It then overwrites the parent's entry in commands. To require a fresh name, check 'name' in cls.__dict__ instead of using getattr.