Sub topic 7
Class decorators as a lighter alternative
This chapter assumes you can write a function decorator, know that @deco above a def means f = deco(f), and have seen __init_subclass__ in the earlier chapters. A class decorator uses the same idea on a class. For many jobs it is the lightest tool you can pick, because it needs no metaclass and no special base class.
What a class decorator is
A class decorator is a callable that receives a finished class and returns a class. This:
@deco
class Widget:
passis equivalent to:
class Widget:
pass
Widget = deco(Widget)Python builds the class first, then calls deco with it, then binds the return value to the name Widget. The decorator never sees the class body as it runs. It only sees the result.
That timing is the main difference from the other tools in this tutorial. A metaclass can change how the namespace is collected (__prepare__) or what gets passed to type(). A class decorator can only inspect or modify a class that already exists.
Registering a class
The simplest decorator records the class somewhere and returns it unchanged.
registry = {}
def register(cls):
registry[cls.__name__] = cls
return cls
@register
class Alpha:
pass
@register
class Beta(Alpha):
pass
print(sorted(registry)) # ['Alpha', 'Beta']Because the decorator returns the same object, nothing else about the class changes. This is the safest kind of class decorator.
Decorators with arguments
To configure a decorator, write a factory: a function that takes the arguments and returns the real decorator. The next example generates a __repr__ from a list of field names.
def auto_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
@auto_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)Here auto_repr('x', 'y') runs first and returns decorate. Then decorate(Point) runs. Assigning to cls.__repr__ works because classes are mutable objects, as you saw in the first chapters. The standard library's dataclasses.dataclass and functools.total_ordering follow this same pattern.
Where a decorator runs in class creation
By the time a decorator is called, type.__new__ has already finished. That means every __set_name__ call and every parent __init_subclass__ call has already happened.
Two consequences follow from this order:
- A decorator can rely on the class being complete. It can read attributes that
__init_subclass__added. - A decorator cannot influence anything that happened earlier. If a descriptor needs its name during
__set_name__, the decorator is too late to supply it.
Stacking order
Several decorators apply from the bottom up, like function decorators.
order = []
def first(cls):
order.append('first')
return cls
def second(cls):
order.append('second')
return cls
@second
@first
class Thing:
pass
print(order) # ['first', 'second']The decorator closest to the class runs first. This matters when one decorator depends on what another one adds.
Limits and failure modes
Decorators are not inherited
A decorator runs once, for the class it is written on. Subclasses are not decorated automatically.
registry = []
def register(cls):
registry.append(cls.__name__)
return cls
@register
class Parent:
pass
class Child(Parent):
pass
print(registry) # ['Parent']Child is missing from the registry. With __init_subclass__ on Parent, every subclass would register itself, but Parent itself would not, because the hook runs only for subclasses. Choose a decorator when you want explicit, per-class opt-in. Choose __init_subclass__ or a metaclass when you want the behavior to follow the whole hierarchy.
Be careful with a decorator that sets attributes, such as cls.tagged = True. A subclass finds that attribute through normal inheritance lookup, so it looks as if the subclass was decorated. Your decorator logic still did not run for it. Anything the decorator computes from the class, such as a field list, is stale for subclasses.
Forgetting to return the class
A decorator that falls off the end returns None, and then the class name is bound to None.
Descriptors added after creation do not get `__set_name__`
Python calls __set_name__ only while type.__new__ builds the class. If your decorator attaches a descriptor with setattr, nobody calls the hook for you.
class Field:
def __set_name__(self, owner, name):
self.name = name
def add_field(name):
def decorate(cls):
setattr(cls, name, Field())
return cls
return decorate
@add_field('email')
class User:
pass
print(hasattr(User.email, 'name')) # False
User.email.__set_name__(User, 'email')
print(User.email.name) # emailThe fix is to call __set_name__ yourself inside the decorator, right after setattr. Do the same for any other protocol that the class-creation machinery normally handles for you.
Replacing the class instead of modifying it
A decorator may return a different class. This is legal, and dataclass(slots=True) does it, but it has a cost. Methods that use zero-argument super() keep a hidden reference to the original class, and that reference becomes wrong.
def rebuild(cls):
namespace = {
k: v for k, v in vars(cls).items()
if k not in ('__dict__', '__weakref__')
}
return type(cls.__name__, cls.__bases__, namespace)
class Base:
def greet(self):
return 'base'
@rebuild
class Child(Base):
def greet(self):
return super().greet()
try:
Child().greet()
except TypeError:
print('TypeError: super() still points at the old class')The greet function was compiled with a __class__ cell that refers to the original Child. The new class is not a subclass of the original, so super() rejects the instance. Other problems come from replacement too. Any reference to the original class that was saved before the decorator ran, such as a registry entry added by an earlier decorator, now points to the wrong object. Modify and return the same class whenever you can. Replace it only when you must, as with __slots__, and document that the decorator does so.
Decorators and metaclasses
A class decorator works on classes with any metaclass, because it only calls the decorator with the final class object. It cannot change the metaclass, since the class already exists. If a decorator needs a different metaclass, you have to restructure the class definition itself, and at that point a base class or metaclass is the better design.
Comparing the three tools
| Need | Class decorator | `__init_subclass__` | Metaclass |
|---|---|---|---|
| Runs for the decorated class itself | Yes | No, only subclasses | Yes |
| Runs for all subclasses automatically | No | Yes | Yes |
| Requires changing the base class | No | Yes | Yes |
| Can change the class body namespace | No | No | Yes, via `__prepare__` |
| Can control instance creation (`__call__`) | No | No | Yes |
| Risk of metaclass conflicts | None | None | Yes |
| Visible at the class definition site | Yes, above the `class` line | Only through the base class | Only through the `metaclass=` argument |
Use a class decorator when you want to opt in per class, when you want the behavior to be visible right where the class is defined, or when you are adding features to classes you do not control. Libraries such as dataclasses choose this design because users can apply it to any class without changing its bases.
A decorator and a hook together
The two tools combine well. A base class can use __init_subclass__ for validation that every subclass needs, while individual classes opt into extras by decorator.
class Model:
def __init_subclass__(cls, /, **kwargs):
super().__init_subclass__(**kwargs)
if not hasattr(cls, 'table'):
raise TypeError(f'{cls.__name__} must define table')
def audited(cls):
original = cls.save
def save(self):
print(f'saving {type(self).__name__}')
return original(self)
cls.save = save
return cls
@audited
class Order(Model):
table = 'orders'
def save(self):
return 'ok'
print(Order().save())
# saving Order
# okThe validation runs during class creation, before the decorator. The decorator then wraps save on the finished class. Because audited replaces cls.save on that one class only, subclasses of Order that override save are not audited.
Exercise
You write @register on class Parent to add it to a registry, then define class Child(Parent). Why is Child missing from the registry, and what is the smallest change that would register every subclass of Parent automatically?
Show answer
A class decorator runs once, for the class it is written on, and subclasses do not inherit that call. To register every subclass, remove the decorator and define __init_subclass__ on Parent that stores cls in the registry. That hook runs for each subclass, but not for Parent itself, so register Parent separately if you need it.
Exercise
A class decorator uses setattr(cls, 'email', Field()), and Field defines __set_name__ to record its attribute name. After decoration, Field has no name recorded. Why, and how do you fix the decorator?
Show answer
Python calls __set_name__ only while type.__new__ creates the class, and the decorator runs after that. Adding the descriptor with setattr later skips the hook. Fix it by creating the descriptor in a variable, calling setattr(cls, name, descriptor), and then calling descriptor.__set_name__(cls, name) yourself.
Exercise
A decorator returns a brand-new class built with type(cls.__name__, cls.__bases__, namespace). Afterwards a method that calls super().method() raises TypeError. What causes it?
Show answer
Zero-argument super() uses a __class__ cell that was created when the original class was defined, so it still points to the original class. The instance now belongs to the new class, which is not a subclass of the original, so super() rejects it. Avoid the problem by modifying and returning the original class, or use explicit super(NewClass, self) only if you control how the replacement is built.