Sub topic 10
Class-based decorators and keeping state
This chapter shows how to write a decorator as a class, why that suits decorators that remember things between calls, and where it behaves differently from a function-based decorator. It assumes you can write a closure-based decorator that forwards *args and **kwargs, and that you know why functools.wraps matters. It also assumes you are comfortable with __init__ and with defining methods on a class.
Why use a class at all
A function-based decorator can keep state in a closure, but that state is hard to see and hard to reach from outside. A class stores state as ordinary attributes. You can read them, reset them, and add methods that work on them.
The pieces fit together because of how Python treats the @ syntax. Writing @Something above a function means func = Something(func). Something only has to be callable with one argument and return a callable. A class meets both requirements. Calling it creates an instance, and an instance is callable if its class defines __call__.
A counting decorator
This is the standard example. The decorated name ends up bound to an instance of CountCalls, not to a function.
import functools
class CountCalls:
def __init__(self, func):
functools.update_wrapper(self, func)
self.func = func
self.calls = 0
def __call__(self, *args, **kwargs):
self.calls += 1
return self.func(*args, **kwargs)
@CountCalls
def ping():
"""Return a fixed reply."""
return "pong"
ping()
ping()
print(ping.calls) # 2
print(ping.__name__) # ping
print(ping.__doc__) # Return a fixed reply.The two methods do different jobs:
__init__runs once, at decoration time. It receives the function and sets up the state.__call__runs on every call toping(). It does the extra work, then forwards to the original function.
update_wrapper instead of wraps
@functools.wraps(func) is meant to decorate the wrapper function you define. Here there is no inner function. The wrapper is the instance. functools.update_wrapper(self, func) does the same copying onto an object you already have. It copies __name__, __qualname__, __doc__, __module__, and merges func.__dict__ into the instance's __dict__. It also sets __wrapped__, which tools such as inspect.signature follow to find the original signature.
Call update_wrapper before you assign your own attributes. That way a stray attribute on the original function cannot overwrite self.calls.
Closure state versus instance state
The same counter can be written as a closure. The two versions compare like this.
import functools
def count_calls(func):
calls = 0
@functools.wraps(func)
def wrapper(*args, **kwargs):
nonlocal calls
calls += 1
return func(*args, **kwargs)
return wrapperIn this version calls cannot be read from outside, because it is a closure variable. You can expose it by setting wrapper.calls, but you then have to update it through the function attribute. The class version gives you this for free.
| Need | Closure | Class |
|---|---|---|
| Simple wrapper, no state | Shorter and idiomatic | More code than necessary |
| State visible to callers | Needs function attributes | Plain attributes |
| Extra operations such as `reset()` | Awkward | Ordinary methods |
| Works on methods | Yes, functions bind automatically | No, needs `__get__` (see below) |
| Inspect state in a debugger | Hidden in `__closure__` | Visible on the instance |
Use a closure when the decorator has no state or the state is private. Use a class when callers or tests need to read or reset the state.
State belongs to one decoration
Each use of @CountCalls creates a new instance. Two decorated functions therefore have separate counters. State is shared only between calls to the same decorated function. If the function is called from several threads, self.calls += 1 is not atomic. Guard it with a threading.Lock when the count must be exact.
Class-based decorators that take arguments
When the decorator needs its own settings, the class receives them in __init__. The function is then passed to __call__. This reverses the roles from the previous example.
import functools
class LimitCalls:
def __init__(self, max_calls):
self.max_calls = max_calls
def __call__(self, func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if wrapper.calls >= self.max_calls:
raise RuntimeError(
f"{func.__name__} may be called at most "
f"{self.max_calls} times"
)
wrapper.calls += 1
return func(*args, **kwargs)
wrapper.calls = 0
return wrapper
@LimitCalls(max_calls=2)
def connect():
return "connected"
print(connect()) # connected
print(connect()) # connected
try:
connect()
except RuntimeError as error:
print(error) # connect may be called at most 2 times@LimitCalls(max_calls=2) first builds an instance, then applies that instance to connect. The class plays the part that the outer function plays in a decorator factory. The instance holds the settings. The counter lives on each wrapper, so one LimitCalls instance can decorate several functions without them sharing a count.
Notice that wrapper is a real function here. Because of that, this form does not have the method problem described next.
The method gotcha
Plain functions defined in a class become bound methods through Python's descriptor protocol. A function has a __get__ method, and attribute lookup uses it to supply self. An instance of CountCalls has no __get__. When it decorates a method, obj.method returns the CountCalls instance unchanged, and self is never passed. The call then fails with a TypeError about a missing self argument.
The fix is to define __get__ and return a bound version of the instance.
import functools
import types
class CountCalls:
def __init__(self, func):
functools.update_wrapper(self, func)
self.func = func
self.calls = 0
def __call__(self, *args, **kwargs):
self.calls += 1
return self.func(*args, **kwargs)
def __get__(self, instance, owner=None):
if instance is None:
return self
return types.MethodType(self, instance)
class Greeter:
def __init__(self, name):
self.name = name
@CountCalls
def hello(self):
return f"hi, {self.name}"
a = Greeter("Ada")
b = Greeter("Bo")
print(a.hello()) # hi, Ada
print(b.hello()) # hi, Bo
print(Greeter.hello.calls) # 2When you access a.hello, Python calls __get__(a, Greeter). types.MethodType(self, a) builds a bound object that passes a as the first argument whenever it is called. Accessing Greeter.hello on the class gives instance as None, so the decorator returns itself and you can read .calls.
Choosing between the forms
- Use a function-based decorator when you only wrap behavior and hold no state that outsiders need.
- Use a class with
__init__(self, func)when the decorator has visible state and needs no arguments of its own. - Use a class with
__init__(self, settings)and__call__(self, func)when you need arguments. Return a real function from__call__so methods keep working. - Add
__get__if a class that wraps the function directly must also decorate methods.
Common mistakes
- Forgetting
update_wrapper. The instance then has no__name__or__doc__of the original, andhelp()shows the class's documentation instead. - Mixing up the two forms.
@LimitCallswithout parentheses passes the function to__init__asmax_calls. Nothing fails until the first call, which then fails confusingly. - Sharing mutable class attributes. A list or dict defined in the class body is shared by every decoration. Create it inside
__init__. - Assuming
isinstance(ping, types.FunctionType). The decorated name is an instance, so checks that expect a function returnFalse.inspect.iscoroutinefunctionalso returnsFalsefor a class that wraps an async function, unless you handle it.
Exercise
You apply @CountCalls to two different functions, alpha and beta, and call alpha three times and beta once. What are alpha.calls and beta.calls, and why? Then explain what goes wrong if you apply the same CountCalls class, without _get_, to a method defined inside a class.
Show answer
alpha.calls is 3 and beta.calls is 1. Each use of @CountCalls creates a new instance, so each decorated function has its own counter in its own instance attribute. On a method, the decorated name becomes a CountCalls instance, which has no _get, so Python does not bind the object as self. The call reaches the original function without self and raises a TypeError about a missing argument. Adding a get_ that returns types.MethodType(self, instance) fixes it.