Today I Learned 1 min read
TIL - Python's __init_subclass__ is a Lightweight Plugin System
Learn how Python's __init_subclass__ hook (Python 3.6+) lets you auto-register subclasses into a plugin registry — no metaclass required. Includes a working code example.
__init_subclass__ is called whenever a class is subclassed. This lets you register subclasses automatically without metaclass magic.
class Plugin:
_registry = {}
def __init_subclass__(cls, name: str, **kwargs):
super().__init_subclass__(**kwargs)
Plugin._registry[name] = cls
class JSONPlugin(Plugin, name="json"):
pass
class XMLPlugin(Plugin, name="xml"):
pass
print(Plugin._registry) # {'json': JSONPlugin, 'xml': XMLPlugin}python
Great for building extensible framework components.