ZetCode

Python __init_subclass__ Method

Last modified November 18, 2026 Python 3.15

Python calls __init_subclass__ on the base class whenever a subclass is defined. It is a simple alternative to a metaclass for tasks such as registration, validation, and declarative configuration. This article shows when the hook runs, how class keywords reach it, and several complete patterns you can reuse.

When the hook runs

The call happens while the class statement is executing, before any instance of the new class exists. The method receives the new class as its first argument; no @classmethod decorator is needed. The print below is a side effect of defining Child.

basic_init_subclass.py
class Base:
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        print("created", cls.__name__)


print("before")
class Child(Base):
    pass
print("after")

The message appears between the two prints, so the hook runs at class definition time. cls is the Child class itself, not an instance. Calling super().__init_subclass__() is the standard way to keep the chain working for further subclasses.

$ python basic_init_subclass.py
before
created Child
after

Class keywords and class attributes

Keywords written in the class header are passed to __init_subclass__ after the new class. The hook can use them to set attributes on the subclass before it is returned to the caller.

class_keywords.py
class Base:
    def __init_subclass__(cls, label=None, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.label = label or cls.__name__
        print(cls.__name__, "->", cls.label)


class Worker(Base, label="worker"):
    pass


class Default(Base):
    pass


print(Worker.label, Default.label)

label="worker" in the class header arrives as a keyword argument. Without it, label is None and the hook falls back to the class name. Forwarding **kwargs to super() keeps other hooks in the hierarchy happy.

$ python class_keywords.py
Worker -> worker
Default -> Default
worker Default

Automatic class registration

The most common use is maintaining a list of subclasses. Each class that inherits from the base adds itself as soon as it is defined, so callers never have to register it separately.

registration.py
class Plugin:
    plugins = []

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        Plugin.plugins.append(cls.__name__)


class Alpha(Plugin):
    pass


class Beta(Plugin):
    pass


print(Plugin.plugins)

The registry holds names rather than class objects, which keeps the output readable and reproducible. In real code you would store the classes themselves and use them to build instances. Note that the order reflects the order of the class statements.

$ python registration.py
['Alpha', 'Beta']

A named registry with duplicate detection

A registry keyed by name can reject duplicates and offer a factory. The check runs at definition time, so a conflicting plugin fails when the module is imported rather than much later at runtime.

named_registry.py
class Registry:
    registry = {}

    def __init_subclass__(cls, key=None, **kwargs):
        super().__init_subclass__(**kwargs)
        name = key or cls.__name__.lower()
        if name in Registry.registry:
            raise ValueError(f"duplicate key {name!r}")
        Registry.registry[name] = cls.__name__

    @classmethod
    def create(cls, key):
        return cls.registry[key]


class Db(Registry, key="db"):
    pass


class Cache(Registry, key="cache"):
    pass


print(sorted(Registry.registry))
print(Registry.create("db"))
try:
    class Duplicate(Registry, key="db"):
        pass
except ValueError as e:
    print(type(e).__name__, e)

Both plugins registered under their explicit keys. Defining a third class with key="db" raises ValueError immediately, and the dictionary still contains the two original entries. Sorting the keys makes the printed line independent of insertion order.

$ python named_registry.py
['cache', 'db']
Db
ValueError duplicate key 'db'

Validating subclasses

The hook can enforce a contract at class creation time. Here every shape must define an area method; a class that forgets it is rejected before anyone can instantiate it.

validate_subclass.py
class Shape:
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        if not hasattr(cls, "area"):
            raise TypeError(f"{cls.__name__} must define area()")


try:
    class Bad(Shape):
        pass
except TypeError as e:
    print(type(e).__name__, e)


class Circle(Shape):
    def area(self):
        return 3.14


print("Circle ok")

The incomplete class raises during the class statement and is never bound to a name. Circle defines the method and is accepted. Failing at definition time gives a much more direct error than discovering the missing method later in production code.

$ python validate_subclass.py
TypeError Bad must define area()
Circle ok

Cooperative inheritance

When both a base and an intermediate class define the hook, the subclass's hook runs first and super() continues the chain. Each level can do its own work and then delegate.

cooperative_subclass.py
class Base:
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        print("Base hook for", cls.__name__)


class Middle(Base):
    def __init_subclass__(cls, **kwargs):
        print("Middle hook for", cls.__name__)
        super().__init_subclass__(**kwargs)


class Leaf(Middle):
    pass

Defining Middle calls the Base hook once. Defining Leaf calls Middle first, which then calls Base through super(). Omitting the super() call would silently skip the base hook.

$ python cooperative_subclass.py
Base hook for Middle
Middle hook for Leaf
Base hook for Leaf

Inspecting the new class

Because the hook receives the finished class object, it can inspect the method resolution order or any attributes defined in the class body. The example prints the MRO to confirm the hook sees the complete class.

inspect_subclass.py
class Base:
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        chain = [c.__name__ for c in cls.__mro__]
        print("defining", cls.__name__, "mro:", chain)


class Child(Base):
    version = 2

The MRO already contains Child, Base and object when the hook runs. Attributes from the class body are available too, so a hook could validate version or copy it into a shared registry.

$ python inspect_subclass.py
defining Child mro: ['Child', 'Base', 'object']

Best practices

Keep these points in mind when customizing class creation:

Source

object.__init_subclass__ - Python documentation

Customizing class creation - Python documentation

PEP 487 - Simpler customization of class creation

In this article we have implemented the __init_subclass__ hook. We have covered when it runs, class keywords, registration, named registries, validation, cooperative inheritance, and inspecting the new class. For related topics, see Python __init__ method, Python __new__ method, and Python metaclasses.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.