Python › Metaclasses & Class Customization

How does __init_subclass__ provide a simpler alternative to metaclasses for many customization needs?

Intermediate

Answer

__init_subclass__(cls, **kwargs) is a classmethod automatically called whenever a subclass is defined, letting you hook into subclass creation (validation, registration, attribute injection) without writing a full metaclass. It's simpler because you just define it in the base class, and Python 3.6+ handles the rest -- covering the majority of use cases that used to require a custom metaclass.
class Plugin:
    registry = []
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        Plugin.registry.append(cls)

class MyPlugin(Plugin):
    pass

print(Plugin.registry)  # [<class 'MyPlugin'>]
Real-world example A web framework uses __init_subclass__ on a base View class to automatically register every route handler subclass, replacing what older versions implemented with a metaclass.

Common follow-ups: What can metaclasses do that __init_subclass__ cannot?;How do class keyword arguments work with __init_subclass__?