Register Subclasses with __init_subclass__
Core idea
init_subclass is a class creation hook defined on a base; it receives each newly created subclass as cls. It is implicitly treated as a class method. Use it for inherited registration or validation policies without introducing a metaclass. Consume your own class-definition keywords and forward remaining keywords through super().init_subclass(**kwargs) so cooperating bases can process them.
class Handler: registry = {} def __init_subclass__(cls, *, kind, **kwargs): super().__init_subclass__(**kwargs) if kind in Handler.registry: raise ValueError('duplicate kind') Handler.registry[kind] = clsclass CsvHandler(Handler, kind='csv'): passclass JsonHandler(Handler, kind='json'): passprint(sorted(Handler.registry))print(Handler.registry['csv'] is CsvHandler)The hook executes at class definition time and stores the class, not an instance. All subclasses of Handler in this design must supply kind.
Compose two keyword policies
class Region: def __init_subclass__(cls, *, region, **kwargs): super().__init_subclass__(**kwargs) cls.region = regionclass Priority: def __init_subclass__(cls, *, priority, **kwargs): super().__init_subclass__(**kwargs) cls.priority = priorityclass Job(Region, Priority, region='west', priority=2): passprint(Job.region, Job.priority)The first hook forwards priority to the next base in the MRO. Each consumes only its own keyword.
Common mistake
Do not forward a consumed keyword again: object.init_subclass rejects unexpected keywords. Registration is a side effect of definition, not an instance initialization step; avoid costly external work there.
Practice
Add a handler with a duplicate kind inside try/except and confirm registration rejects it without replacing the earlier entry.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Class creation hooks
Check your understanding of class creation hooks.
What is printed?
events=[]class A: def __init_subclass__(cls): super().__init_subclass__(); events.append(cls.__name__)class B(A): passB(); B()print(events)What is printed?
class A: def __init_subclass__(cls, *, tag, **kw): super().__init_subclass__(**kw); cls.tag=tagclass B(A,tag='x'): passprint(B.tag)When is the hook on Handler called?
Why forward unused class keywords with super()?