Python __init_subclass__: Customizing Class Creation
Learn how Python's __init_subclass__ hook works, when to use it, and how it differs from metaclasses with practical examples.

Python's __init_subclass__ is a classmethod that is invoked whenever a subclass of the class is defined. It provides a clean hook for customizing subclass creation without introducing a full metaclass. This article explains how it works, where it fits, and what to watch out for.
What Is init_subclass?
__init_subclass__ is a special method that Python calls after a subclass is created. It is implicitly treated as a class method, so it receives the newly created subclass as cls, followed by any keyword arguments that were passed in the class definition. The method is defined on the base class and is automatically invoked for every subclass, including indirect ones.
The hook was introduced in Python 3.6 and gives developers a way to observe or modify subclasses at definition time. Unlike a metaclass, which controls the entire class creation process, __init_subclass__ is a single callback that runs after the class object exists.
A Minimal Example
The simplest way to see the hook in action is to define a base class that prints or records its subclasses.
class Base:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
print(f'New subclass: {cls.__name__}')
class Child(Base):
passWhen Child is defined, the output is:
New subclass: Child
The super().__init_subclass__(**kwargs) call is important. It ensures that the hook chain continues up the inheritance hierarchy. If you omit it, any base class above the current one will not receive the notification.
How init_subclass Differs from Metaclasses
Metaclasses are the most powerful way to customize class creation. They can intercept the class body, modify attributes, and control the entire lifecycle. However, they are also more complex to write and debug. __init_subclass__ is a lighter alternative that covers a common subset of use cases.
With a metaclass, you typically define a class that inherits from type and override __new__ or __init__. Then you set that metaclass on a base class. Every subclass inherits the metaclass, and the metaclass's methods run during class creation. __init_subclass__ is just a classmethod on the base class, so it does not require an extra layer of indirection.
The choice between the two depends on what you need. If you only need to react to subclass creation, __init_subclass__ is simpler. If you need to control the class object itself, such as changing its __dict__ or intercepting attribute access, a metaclass is necessary.
Practical Use Cases
Subclass Registration
A common pattern is to maintain a registry of all subclasses. This is useful for plugin systems or factory functions.
class PluginBase:
registry = {}
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
cls.registry[cls.__name__] = cls
class FirstPlugin(PluginBase):
pass
class SecondPlugin(PluginBase):
pass
print(PluginBase.registry)
# {'FirstPlugin': <class '__main__.FirstPlugin'>, 'SecondPlugin': <class '__main__.SecondPlugin'>}Validation of Subclass Attributes
You can enforce that subclasses define certain attributes or methods.
class ValidatedBase:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
if not hasattr(cls, 'required_attr'):
raise TypeError(f'{cls.__name__} must define required_attr')
class GoodChild(ValidatedBase):
required_attr = 'present'
# class MissingChild(ValidatedBase):
# pass # Would raise TypeError: MissingChild must define required_attrValidatedBase itself does not define required_attr, so subclasses must provide it or inherit it from another class. If they do not, the hook raises TypeError when the class is defined.
Setting Default Class Attributes
You can automatically set class-level defaults on subclasses.
class Base:
defaults = {'timeout': 30}
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
for key, value in cls.defaults.items():
if not hasattr(cls, key):
setattr(cls, key, value)
class Service(Base):
pass
print(Service.timeout) # 30Common Pitfalls and Edge Cases
__init_subclass__ is not called for the base class itself. It only fires for subclasses. This is usually what you want, but it means you cannot rely on it to initialize the base class.
The hook is called for every subclass, including those that are themselves bases for further subclasses. If you override __init_subclass__ in a subclass, you must call super().__init_subclass__ to ensure the chain is preserved. Otherwise, the base class's hook will not run.
Keyword arguments passed in the class definition are forwarded to __init_subclass__. This allows you to accept custom parameters. In an override, pass any keyword arguments you do not consume to super().__init_subclass__ so hooks on ancestor classes still receive them.
class Base:
def __init_subclass__(cls, *, custom_option=None, **kwargs):
super().__init_subclass__(**kwargs)
cls.custom_option = custom_option
class Child(Base, custom_option='enabled'):
pass
print(Child.custom_option) # enabledIf you forget to accept **kwargs in your override, you will get a TypeError when a subclass passes extra keyword arguments.
Performance and Maintainability Considerations
The overhead of __init_subclass__ is minimal because it is only called once per class definition, not per instance. However, if you perform heavy operations inside the hook, such as database queries or file I/O, it will slow down module import time. Keep the hook lightweight.
From a maintainability perspective, __init_subclass__ centralizes subclass-related logic in one place. This can reduce duplication, but it can also make the base class harder to understand if the hook does too much. Prefer small, focused hooks that do one thing well.
When to Choose init_subclass Over Metaclasses
Use __init_subclass__ when you need to react to subclass creation and the behavior fits into a single callback. It is ideal for registration, validation, and setting defaults.
Use a metaclass when you need to control the class object itself, such as modifying its __dict__, intercepting attribute access, or implementing a DSL. Metaclasses are also necessary if you need to affect the base class itself, because __init_subclass__ only runs for subclasses.
In practice, __init_subclass__ is often the right tool because it is simpler to write, test, and debug. It keeps the inheritance hierarchy clean and avoids the complexity of metaclasses unless they are truly required.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.