Sub topic 7
Class decorators as a lighter alternative
This chapter assumes you can write decorators for functions, define classes with inheritance, and have seen __init_subclass__ and __set_name__ in the earlier chapters. A class decorator is the simplest way to change a class after Python has built it, and it needs no metaclass.
What a class decorator is
A class decorator is a callable that takes a class and returns a class, usually the same one. This code:
@decorator
class Thing:
...is the same as writing Thing = decorator(Thing) after the class statement. The decorator receives a fully built class object. It can read the class, change it, or replace it.
Registering a class
The simplest decorator records the class somewhere and returns it unchanged.
registry = {}
def register(cls):
registry[cls.__name__.lower()] = cls
return cls
@register
class CsvPlugin:
pass
class CsvChild(CsvPlugin):
pass
print(sorted(registry)) # ['csvplugin']CsvChild is not in the registry. A decorator runs once, for the class it is written on. It does not follow inheritance. This is the main difference from __init_subclass__, which runs for every subclass.
Decorators that take arguments
To configure a class decorator, write a function that returns the decorator. The outer call takes your arguments, and the inner function takes the class.
def add_repr(*fields):
def decorate(cls):
def __repr__(self):
parts = ', '.join(f'{f}={getattr(self, f)!r}' for f in fields)
return f'{cls.__name__}({parts})'
cls.__repr__ = __repr__
return cls
return decorate
@add_repr('x', 'y')
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
print(Point(1, 2)) # Point(x=1, y=2)Assigning to cls.__repr__ works because classes are ordinary mutable objects. This is the same idea as dataclasses.dataclass, which adds __init__, __repr__ and __eq__ this way.
When the decorator runs
A decorator runs last, after the class exists and after the other hooks have finished.
class Base:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
print('__init_subclass__')
class Marker:
def __set_name__(self, owner, name):
print('__set_name__')
def deco(cls):
print('decorator')
return cls
@deco
class Thing(Base):
marker = Marker()This prints __set_name__, then __init_subclass__, then decorator.
Because the decorator runs last, it sees the finished class, including anything the other hooks added.
Common errors
- Forgetting
return cls. The decorator then returnsNone, and the class name is bound toNone. The failure shows up later asTypeError: 'NoneType' object is not callable. - Expecting inheritance. Subclasses are not decorated, so a rule enforced by a decorator is silently skipped for them. Use
__init_subclass__or a metaclass when subclasses must be covered. - Replacing the class with a new one. If the decorator returns a different class, such as a rebuilt class with
__slots__, methods that use zero-argumentsuper()still point at the old class through the hidden__class__cell. This breakssuper()in those methods. Prefer modifying and returning the same class. - Missing parentheses. With a decorator factory like
add_repr, writing@add_reprinstead of@add_repr('x')passes the class as the first field name.
When a decorator is the right tool
Choose a decorator when the change applies to one class at a time, when you want the effect to be visible at the class definition, or when you want to reuse the logic on classes you do not control. Choose __init_subclass__ when every subclass in a hierarchy must be handled. A decorator cannot change how the class body runs or what type is used to build the class. Those jobs need a metaclass.
Exercise
You write a @register class decorator and apply it to Base. Later, Child(Base) is defined, but Child is missing from the registry. Why, and what is the smallest change that registers every subclass automatically?
Show answer
A class decorator runs once, on the class it decorates, and is not inherited. Move the registration into Base.__init_subclass__, which Python calls each time a subclass is defined. Call super().__init_subclass__(**kwargs) inside it.