Sub topic 10
Class-based decorators and keeping state
This chapter assumes you can write a function decorator with functools.wraps and apply it with @. It also assumes you know what a closure is and how __init__ and __call__ work in a class.
Why use a class
A function decorator can keep state in a closure, but that state is hard to reach from outside. A class-based decorator stores state as instance attributes, so you can read it, reset it, or extend it with methods.
Two facts from earlier chapters make this work:
@decoabovedef fmeansf = deco(f).- Any object with a
__call__method can be called like a function.
So if deco is a class, deco(f) builds an instance, and that instance replaces f. Calling f(...) then runs the instance's __call__.
A call counter
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 "pong"
ping()
ping()
print(ping.calls) # 2
print(ping.__name__) # ping__init__ runs once, at decoration time. __call__ runs on every call. The counter lives on the instance, so ping.calls reads it directly.
You can't use @functools.wraps here, because there is no inner function to decorate. functools.update_wrapper(self, func) does the same job: it copies __name__, __doc__ and other metadata onto the instance.
The method problem
A plain function becomes a bound method when you access it through an instance. Python does this through the function's __get__ method. Your decorator instance has no __get__, so decorating a method breaks it. The instance is never passed as self, and the call fails with a TypeError about a missing self.
To fix it, add __get__ so the decorator binds itself like a function would:
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:
@CountCalls
def hello(self):
return "hi"
a = Greeter()
b = Greeter()
a.hello()
b.hello()
print(Greeter.hello.calls) # 2types.MethodType(self, instance) makes a bound method whose function is the decorator instance, so __call__ receives instance as its first argument.
Where the state lives
This sharing is also what makes class-based decorators useful for things like rate limiters, call histories, and caches. Everything the decorator remembers is in one place.
Choosing between the two styles
| Need | Better fit |
|---|---|
| Simple wrapping, no state | Function decorator |
| State you want to inspect or reset from outside | Class-based decorator |
| Decorating methods | Function decorator, or a class with `__get__` |
| Several helper methods, such as `reset()` | Class-based decorator |
Exercise
You write a class-based decorator and apply it to a method of a class. Calling obj.method() raises a TypeError about a missing self. What is missing from the decorator class, and what should it return when instance is not None?
Show answer
The decorator class needs a __get__(self, instance, owner=None) method. When instance is not None, it should return types.MethodType(self, instance), which binds the instance as the first argument. When instance is None (access through the class), it should return self.
Exercise
Add a reset() method to the first CountCalls example that sets the counter back to zero. Why is this easy with a class and awkward with a function decorator?
Show answer
Add def reset(self): self.calls = 0. Then ping.reset() works, because ping is the decorator instance. A function decorator would have to attach a function to the wrapper, such as wrapper.reset = ..., and use nonlocal to change closure state, which is harder to read.