Sub topic 11
Decorating classes
This chapter assumes you know how to write a function decorator, how the @ syntax works, and how classes define methods and attributes. A decorator can also be applied to a class. The idea is the same as for functions, but the decorator receives a class object instead of a function.
What a class decorator receives
When Python reaches a decorated class statement, it runs the class body and builds the class object. It then passes that object to the decorator and binds the class name to whatever the decorator returns. This is the same reassignment you saw with functions, as if you had written Name = decorator(Name).
Because the decorator runs once, at class definition time, it is a good place for one-time setup. Nothing is added to each instance or each method call.
Example: a plugin registry
The simplest class decorator records the class somewhere and returns it unchanged.
REGISTRY = {}
def register(cls):
REGISTRY[cls.__name__] = cls
return cls
@register
class CsvExporter:
pass
@register
class JsonExporter:
pass
print(sorted(REGISTRY)) # ['CsvExporter', 'JsonExporter']Importing the module is enough to fill REGISTRY. Other code can then look up an exporter by name without a hand-written list that someone must remember to update.
Example: adding behavior to a class
A class decorator can also modify the class by attaching attributes or methods. This one gives any class a readable __repr__.
def auto_repr(cls):
def __repr__(self):
fields = ", ".join(f"{k}={v!r}" for k, v in vars(self).items())
return f"{cls.__name__}({fields})"
cls.__repr__ = __repr__
return cls
@auto_repr
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
print(Point(1, 2)) # Point(x=1, y=2)The inner __repr__ is a closure over cls, so it can use the class name. Assigning it to cls.__repr__ makes it a normal method on every instance.
Modify or replace
A class decorator can do one of two things.
| Approach | What the decorator returns | Effect |
|---|---|---|
| Modify in place | The same `cls` | `isinstance` checks, subclassing, and the class name all keep working |
| Replace | A new class or a wrapper | The name now refers to something else, which can surprise callers |
Prefer modifying in place. If you return a wrapper function or a different object, isinstance(obj, Point) can break, because Point may no longer be a class. Subclassing can break too.
A class decorator can take arguments in the same way a function decorator can. Write a factory that returns the decorator, such as @register_as("csv"), and keep the same return cls at the end of the innermost function.
Class decorators or alternatives
Class decorators are good for registration and for adding a fixed set of methods or attributes. They have two limits:
- They run after the class is fully built, so they cannot change how the class body is evaluated.
- They are not inherited. A subclass of
Pointis not decorated again, so a registry would not see it.
If you need to react to every subclass automatically, define __init_subclass__ on the base class, or use a metaclass for deeper control. For most registration and method-adding tasks, a class decorator is the simpler choice.
Common mistakes
- Forgetting
return cls. The function then returnsNone, and the class name becomesNone. The error appears later, asTypeError: 'NoneType' object is not callable, far from the cause. - Expecting inheritance. The decorator ran once, on the class you decorated. Subclasses need their own decoration.
- Decorating instead of subclassing for the wrong reason. If the change needs
super()or must override behavior polymorphically, a mixin or subclass may fit better.
Exercise
In the auto_repr example, suppose you delete the line "return cls". What does the name Point refer to afterward, and what happens when you run Point(1, 2)?
Show answer
The @ syntax binds Point to the decorator's return value. Without "return cls", the function returns None, so Point is None. Running Point(1, 2) raises TypeError: 'NoneType' object is not callable.
Exercise
Write a class decorator factory registeras(name) that stores the class in REGISTRY under the given name instead of its name_, and returns the class unchanged.
Show answer
def registeras(name): def decorator(cls): REGISTRY[name] = cls return cls return decorator Usage: @registeras("csv") above class CsvExporter stores it under REGISTRY["csv"].