Lesson · Advanced Object Model
__init_subclass__
75 min read__init_subclass__
`__init_subclass__` runs when a subclass is created and is a lightweight hook for registration, validation, and conventions. It solves many framework problems without a custom metaclass.
Learning goals
- Describe when
__init_subclass__runs, what its first argument is, and which class triggers it. - Pass keyword arguments from a subclass's class statement into the hook and read them in its signature.
- Build a registry that fills itself as subclasses are defined, with no separate registration call.
- Enforce a convention in the hook so a violating subclass fails at definition time.
- Decide when the hook is enough and when a metaclass is genuinely needed.
Mental model
Each subclass definition triggers exactly one hook call on its parent, so behavior attached there reaches every future subclass, including ones written later in other modules. The base itself never triggers its own hook.
Mental model
read it top to bottom
class JsonPlugin(Plugin, name="json"): body executes ↓ subclass object created, keywords held aside Plugin.__init_subclass__(cls=JsonPlugin, name="json") ↓ class statement binds JsonPlugin, registry already updated
Core idea
__init_subclass__ is the language's built-in reaction to subclassing: define it once on a base class, and Python calls it every time a subclass is created, handing over the new class and any keyword arguments from the class statement. That single hook covers most of what frameworks use metaclasses for: registering, validating, and configuring subclasses, while the class keeps its ordinary type. It is the first tool to try for inheritance-driven behavior.
Subclass hooks
__init_subclass__ is a hook that runs once when a subclass of the defining class is created, with the new class passed as cls; Python treats it as an implicit classmethod. It executes after the subclass body has finished, so the namespace is complete, and any keyword arguments written in the subclass's class statement arrive as keyword parameters.
Registration patterns
A registration pattern records each subclass in a shared structure at creation time, usually a dictionary on the base class keyed by a name. Because the hook fires for every subclass automatically, the registry fills itself as modules are imported, and lookups never touch a manually maintained list.
Enforcing subclass conventions
The hook can check each new subclass and raise TypeError before the class finishes being created, so a missing method or attribute fails at definition time instead of at first use. That turns a required convention, such as every plugin defining run, into an automated contract no subclass can skip.
Lightweight alternative to metaclasses
Compared with a metaclass, __init_subclass__ covers registration and validation without replacing the class's type or intercepting creation itself. It composes predictably through inheritance, so a metaclass is worth it only when the class object must be transformed or the same behavior must reach classes that share no common base.
Walkthrough
- The base declares
def __init_subclass__(cls, *, name, **kwargs); the keyword-onlynameparameter is what allowsclass JsonPlugin(Plugin, name="json")to pass data into the hook, and**kwargsforwards everything else. super().__init_subclass__(**kwargs)keeps the hook cooperative, so another class in the hierarchy can define it too and still be called.Plugin.registry[name] = clsruns whileJsonPluginis being created, withclsbound to the new class object; the final print shows a single entry, the stringjsonmapping toJsonPlugin.- Predict before running: the exact contents of
Plugin.registryafter this file, and what changes when a second subclass withname="xml"is added below.
Experiments to try
- Add another subclass,
class XmlPlugin(Plugin, name="xml"): pass, and confirm the registry grows without any extra call. - Drop the
namekeyword from a subclass and read theTypeErrorabout the missing keyword-only argument, noting that it fires at class definition time. - Give the hook a default with
name="generic"and observe that the keyword becomes optional, then decide which contract the registry should enforce. - Define
class Extended(JsonPlugin): passand observe that the hook fires again for the grandchild, raising the missing-keyword error; pass a name and confirm both entries coexist.
Common mistakes
- Naming the first parameter
self: the hook is implicitly a classmethod, so the argument is the new class, and the wrong name suggests instance state that does not exist. - Forgetting
super().__init_subclass__(**kwargs): as soon as another class in the hierarchy defines the hook, its call is silently skipped. - Expecting the hook to run for the defining class: only subclasses trigger it, so the base needs its own registration line if it must appear in the registry.
- Forgetting that registration happens at import time: a subclass module that is never imported has no entries, so lookups fail until something imports it.
Practice: Easy
- Run the worked example and print
Plugin.registry; identify the key and the value of the single entry, and say which class is missing from it. - Add
class XmlPlugin(Plugin, name="xml"): passand predict both keys before rerunning. - Remove the
namekeyword fromJsonPluginand read theTypeError; explain which part of the hook signature produced it.
Practice: Medium
- Add validation to the hook that raises
TypeErrorunless the subclass defines arunmethod; write one compliant subclass and one that fails, and note when the failure appears. - Add a
lookup(name)classmethod toPluginthat returns the registered class or raisesKeyErrorwith a helpful message; test both branches against the registry from the example. - Define
__init_subclass__on two levels of the hierarchy, each adding a different attribute, and verify both run when the lower one forwards**kwargsthroughsuper().
Practice: Hard
- Build a plugin base where each subclass declares
nameandrun; reject duplicate names at definition time, and write three assertions covering success, a duplicate, and a missing method. - Set up a failure lab with three broken subclasses: a missing
namekeyword, a missingrunmethod, and a two-level hierarchy where the middle hook forgetssuper(); explain each error from the hook call order. - Implement the same registry with a metaclass instead, then state one thing the metaclass can do that the hook cannot and one reason the hook version is still preferable for registration.
Lesson checklist
- I can describe exactly when
__init_subclass__fires, what its first argument is, and which class triggers it. - I can pass data from a class statement into the hook with a keyword-only parameter.
- I can build a self-filling registry and explain why it needs no manual registration call.
- I can make a convention fail at definition time and say why that timing helps.
Remember
`__init_subclass__` turns subclassing into a hook: every new subclass calls it once, and the class statement can hand it keyword data like a name. That is enough for registries and convention checks, and the class keeps its ordinary type, which makes the hook easier to reason about than a metaclass whenever both could work.
Interview angles
What is the main purpose of **Subclass hooks**?+
__init_subclass__ is a hook that runs once when a subclass of the defining class is created, with the new class passed as cls; Python treats it as an implicit classmethod. It executes after the subclass body has finished, so the namespace is complete, and any keyword arguments written in the subclass's class statement arrive as keyword parameters.
What should you pay attention to when using **Registration patterns**?+
A registration pattern records each subclass in a shared structure at creation time, usually a dictionary on the base class keyed by a name. Because the hook fires for every subclass automatically, the registry fills itself as modules are imported, and lookups never touch a manually maintained list.
How does **Enforcing subclass conventions** fit into this lesson?+
The hook can check each new subclass and raise TypeError before the class finishes being created, so a missing method or attribute fails at definition time instead of at first use. That turns a required convention, such as every plugin defining run, into an automated contract no subclass can skip.
Why does a registry built with `__init_subclass__` stay empty when a plugin module is never imported?+
The hook runs when a subclass is created, and that happens while its module executes. If nothing imports the module, the class statement never runs, so no registration occurs; registries that must be complete need explicit imports or a discovery step.