Sub topic 12
Putting the tools together
This chapter combines partial, wraps and cache in one program. It assumes you have read the earlier chapters: you know how partial fixes arguments, why functools.wraps keeps a decorated function's name and docstring, and how cache keys results by hashable arguments.
Stacking a wraps-based decorator on a cached function
A decorator written with wraps works on any callable, including one that cache has already wrapped. Decorators apply from the bottom up, so the one closest to def wraps first.
import functools
from functools import cache
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}{args}")
return func(*args, **kwargs)
return wrapper
@log_calls
@cache
def double(n):
return n * 2
double(4)
double(4) # logged again, but the computation is served from the cache
print(double.__name__) # double
print(double.__wrapped__.cache_info()) # CacheInfo(hits=1, misses=1, maxsize=None, currsize=1)Here log_calls sits outside the cache, so it runs on every call. The cache sits inside it and runs the body of double only once for the argument 4.
wraps copies __name__ and __doc__ and sets __wrapped__. It does not give the wrapper the cache's cache_info or cache_clear methods. Calling double.cache_info() here raises AttributeError. You reach the cache through double.__wrapped__, which wraps set for you.
Order decides what the cache sees
Swapping the two decorators changes what each one observes.
| Order (top to bottom) | Logging runs | Cache methods on the result |
|---|---|---|
| `@log_calls` then `@cache` | On every call | Reached through `__wrapped__` |
| `@cache` then `@log_calls` | Only on cache misses | Available directly |
Put the cache on the outside when the extra work is expensive or has side effects you only want once, such as logging a computation or timing it. Put your decorator on the outside when it must see every call, such as for access checks or call counting.
Adding partial
partial also accepts a cached function. The partial is a separate callable, and it passes its stored arguments to the cached function on every call.
import functools
from functools import cache, partial
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"computing {func.__name__}{args} {kwargs}")
return func(*args, **kwargs)
return wrapper
@cache
@log_calls
def scale(n, factor):
"""Multiply n by factor."""
return n * factor
double = partial(scale, factor=2)
print(double(4))
print(double(4))
print(scale(4, 2))
print(scale.cache_info())The output is:
computing scale(4,) {'factor': 2}
8
8
computing scale(4, 2) {}
8
CacheInfo(hits=1, misses=2, maxsize=None, currsize=2)The second double(4) is a hit, so nothing is printed for it. scale(4, 2) is a miss even though it computes the same value. cache builds its key from how the call was written. scale(4, factor=2) and scale(4, 2) produce different keys, so they get separate entries.
For this reason, pick one calling style for a cached function and use it consistently. A partial that fixes an argument by keyword always uses the keyword form, so it never shares entries with positional calls.
Checklist for combined decorators
- Write every custom decorator with
@functools.wraps(func)on the inner function, so names and docstrings survive any number of layers. - Decide which layer must run on every call. That layer goes outside the cache.
- Keep the cache close to the function it memoizes, so its key reflects the real arguments.
- Use
__wrapped__to reachcache_info()andcache_clear()through outer layers. - Keep the cached function pure and its arguments hashable, as covered in the pitfalls chapter.
Exercise
You have @cache above @log_calls on a function f, and you call f(3) three times. How many times does the wrapper from log_calls run, and how would you read the cache statistics?
Show answer
The wrapper runs once, on the first call (a cache miss). The next two calls are hits and never reach it. Because cache is the outermost decorator, f.cache_info() works directly and shows CacheInfo(hits=2, misses=1, maxsize=None, currsize=1).
Exercise
With @log_calls above @cache on double, why does double.cache_info() fail, and what call works instead?
Show answer
wraps copies __name__, __doc__ and the wrapped function's __dict__, and sets __wrapped__. The cache methods are not in that __dict__, so the wrapper does not have them. double.__wrapped__.cache_info() reaches the cache object.