__init_subclass__ in Python
A hook that runs when a subclass is defined — a registry without a metaclass.
class Plugin:
registry = {}
def __init_subclass__(cls, name=None, **kwargs):
super().__init_subclass__(**kwargs)
cls.registry[name or cls.__name__.lower()] = cls
class Csv(Plugin, name="csv"):
pass
class Json(Plugin):
pass
print(sorted(Plugin.registry))
print(Plugin.registry["csv"] is Csv)
How it works
- It is implicitly a classmethod on the parent.
- Keyword arguments in the class statement arrive here.
- Cheaper to read than a metaclass, and usually enough.
Keywords and builtins used here
CsvJsonPlugin__init_subclass__classclsdefpassprintsortedsuper
The run, in numbers
- Lines
- 18
- Characters to type
- 297
- Tokens
- 89
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 49 seconds.
Step 2 of 3 in Class machinery, step 36 of 53 in Pythonic Python.