Sub topic 11
Decorating classes
This chapter assumes you can write a function decorator with functools.wraps, and that you know how the @ syntax reassigns a name. It also assumes you know basic Python classes, including __init__ and instance attributes. A class decorator uses the same mechanism as a function decorator. The difference is that it receives a class instead of a function.
What a class decorator is
A class decorator is a callable that takes a class object and returns something, usually the same class. Python evaluates the whole class statement first, which produces a class object. It then passes that object to the decorator and binds the result to the class name.
This code:
@decorator
class Thing:
passis equivalent to this:
class Thing:
pass
Thing = decorator(Thing)Because the decorator runs once, when the class is defined, class decorators suit setup work. Typical uses are registering the class somewhere, adding methods or attributes, and checking that the class is well formed.
Registering a class
The simplest class decorator records the class and hands it back unchanged. This builds a plugin registry:
REGISTRY = {}
def register(cls):
REGISTRY[cls.__name__] = cls
return cls
@register
class CsvExporter:
pass
@register
class JsonExporter:
pass
print(sorted(REGISTRY)) # ['CsvExporter', 'JsonExporter']Nothing is wrapped here. CsvExporter is still the original class, so isinstance, inheritance, and CsvExporter() all behave as usual. Returning the same class is the safest design, and you should prefer it unless you have a reason to do otherwise.
Modifying a class
Because a class is a mutable object, a decorator can add or replace attributes on it with setattr or plain assignment. This decorator gives any class a readable __repr__ based on its instance attributes:
def add_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
@add_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, which is how it knows the class name. Assigning a plain function to a class attribute turns it into a method, because functions are descriptors that bind self on access.
A decorator that adds methods should usually avoid overwriting ones the author defined on purpose. Check first with "__repr__" in cls.__dict__. The standard library's dataclass follows this convention.
Class decorators that take arguments
The decorator factory pattern from the earlier chapter works unchanged. The outer function takes the configuration, and the inner function takes the class:
PLUGINS = {}
def plugin(name):
def decorator(cls):
PLUGINS[name] = cls
cls.plugin_name = name
return cls
return decorator
@plugin("csv")
class CsvExporter:
pass
print(PLUGINS["csv"] is CsvExporter) # True
print(CsvExporter.plugin_name) # csvHere plugin("csv") runs first and returns decorator. Python then applies decorator to the class. If you write @plugin without the parentheses, the class is passed as name. The class gets stored as a key and plugin returns the inner function, so CsvExporter becomes a plain function. This is the same missing-call mistake that happens with function decorator factories.
A standard-library example: dataclass
dataclasses.dataclass is the most widely used class decorator. It reads the class's annotations and generates __init__, __repr__, and __eq__ for you. It also works with and without arguments:
from dataclasses import FrozenInstanceError, dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
p = Point(1, 2)
print(p) # Point(x=1, y=2)
try:
p.x = 5
except FrozenInstanceError:
print("frozen")dataclass modifies the class in place and returns it, and that is the pattern to copy. Its optional-argument behavior is implemented by checking whether it received a class or keyword arguments.
Returning something other than the class
A decorator can return a different object, but this has costs. A common example is a singleton decorator that replaces the class with a function:
def bad(cls):
def wrapper(*args, **kwargs):
return cls(*args, **kwargs)
return wrapper
@bad
class A:
pass
try:
isinstance(A(), A)
except TypeError as exc:
print(exc) # isinstance() arg 2 must be a type, a tuple of types, or a unionAfter decoration, A is a function, so isinstance(x, A) fails, class B(A) fails, and class attributes are no longer reachable through the name. If you need to change how instances are created, consider these alternatives:
- Override
__new__on the class. - Use a metaclass.
- Return a subclass of
clsfrom the decorator, which keepsisinstanceworking for the original class.
Inheritance and class decorators
A class decorator runs once, for the class it decorates. Subclasses are not decorated automatically, although they inherit any attributes the decorator added.
REGISTRY = {}
def register(cls):
REGISTRY[cls.__name__] = cls
return cls
@register
class Base:
pass
class Child(Base):
pass
print(sorted(REGISTRY)) # ['Base']Child inherits from a registered class but is not in the registry. If you want every subclass handled, use __init_subclass__, which Python calls whenever a subclass is created:
class Plugin:
registry = {}
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
Plugin.registry[cls.__name__] = cls
class A(Plugin):
pass
class B(A):
pass
print(sorted(Plugin.registry)) # ['A', 'B']Choosing between the options
| Need | Best tool | Reason |
|---|---|---|
| Register or tag specific classes | Class decorator | Explicit, and each class opts in |
| Handle every subclass automatically | `__init_subclass__` | Runs for all descendants |
| Control how the class object itself is built | Metaclass | Runs before the class exists |
| Generate boilerplate methods | Class decorator | Simple, and does not change the inheritance chain |
| Wrap every method with the same behavior | Class decorator that loops over methods | See below |
Decorating every method
A class decorator can apply a function decorator to each method. This loops over the class dictionary and rewraps the callables:
import functools
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"calling {func.__qualname__}")
return func(*args, **kwargs)
return wrapper
def log_all_methods(cls):
for name, value in list(vars(cls).items()):
if callable(value) and not name.startswith("__"):
setattr(cls, name, log_calls(value))
return cls
@log_all_methods
class Account:
def deposit(self, amount):
return amount
def withdraw(self, amount):
return -amount
Account().deposit(10) # calling Account.depositThere are several details in this code. It copies the items with list(...) before calling setattr, because changing a dictionary while iterating over it is an error. It skips dunder methods, which are usually not worth logging and can cause recursion. It also relies on callable(value) being true only for plain functions in this class. A staticmethod or classmethod object stored in the class dictionary is not callable on older Python versions (before 3.10 for staticmethod), so a robust version should check the type explicitly.
Common mistakes
- Forgetting
return cls. The class name becomesNone. - Using a factory without calling it.
@plugininstead of@plugin("csv")replaces the class with a function. - Replacing the class with a wrapper function. This breaks
isinstance, subclassing, and class-level access. - Expecting subclasses to be decorated. Use
__init_subclass__when you need that. - Mutating shared state at import time without noticing. A registry fills up as modules are imported, so a class in a module that is never imported will not appear in it.
Exercise
Write a class decorator add_slots_info that adds a class attribute field_count equal to the number of annotated fields in the class (use cls.__annotations__), and returns the same class. What does field_count equal for class P: x: int; y: int?
Show answer
def addslotsinfo(cls): cls.fieldcount = len(cls.annotations); return cls. Applied to P, fieldcount is 2. The decorator returns cls, so P stays a normal class and isinstance checks still work.
Exercise
A teammate writes @register above class Base, then defines class Child(Base). They are surprised that Child is missing from the registry. Explain why and give one fix.
Show answer
A class decorator runs only once, on the class it is written above, so Child is never passed to register. One fix is to define _initsubclass__ on Base and add each new subclass to the registry there. Another is to put @register above Child as well.