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 on each tool. You should also be comfortable with decorators that take *args, **kwargs, and with the rule that cache arguments must be hashable. The new material is about interactions: which layer runs first, which attributes survive stacking, and how to write one decorator that works with and without options.
Stacking a wraps-based decorator on a cache
Decorators apply from the bottom up. In this example, @cache wraps double first. Then @log_calls wraps the cached function.
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):
print("computing")
return n * 2
double(4)
double(4)
print(double.__name__)
print(double.__wrapped__.cache_info())The output is:
calling double(4,)
computing
calling double(4,)
double
CacheInfo(hits=1, misses=1, maxsize=None, currsize=1)The logging wrapper is the outermost layer, so it runs on every call. The cache is the inner layer. It runs the real function once and serves the second call from memory. The name double is correct because wraps copied __name__ from the cached function. That function had already copied it from the original.
The call flow looks like this:
Order changes behavior
Swapping the two decorators changes what the logger sees.
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
@cache
@log_calls
def triple(n):
print("computing")
return n * 3
triple(4)
triple(4)
print(triple.cache_info())The output is:
calling triple(4,)
computing
CacheInfo(hits=1, misses=1, maxsize=None, currsize=1)Now the logger runs only on cache misses, because the cache sits outside it and answers the second call itself. Also, triple.cache_info() works directly, because the outermost object is the cache.
| Order (top to bottom) | Logger runs | `cache_info()` available on the result | Typical use |
|---|---|---|---|
| `@log_calls` over `@cache` | Every call | No, use `__wrapped__.cache_info()` | Counting requests, auditing, rate limiting |
| `@cache` over `@log_calls` | Only on misses | Yes | Measuring real computation, timing the slow path |
Pick the order by asking what the decorator should observe. If it must see every call, put it outside the cache. If it should only see work that was actually done, put it inside.
Why cache_info disappears
In the first example, double.cache_info does not exist. wraps copies __module__, __name__, __qualname__, __doc__, and the __dict__ contents of the wrapped object. It then sets __wrapped__. In CPython, the cached function is a C-implemented object, and cache_info and cache_clear are methods of its type. They are not entries in its __dict__, so they are not copied.
import functools
from functools import cache
def passthrough(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@passthrough
@cache
def square(n):
return n * n
square(3)
print(hasattr(square, "cache_info")) # False in CPython
print(square.__wrapped__.cache_info()) # CacheInfo(hits=0, misses=1, maxsize=None, currsize=1)
square.__wrapped__.cache_clear()__wrapped__ is the supported way to reach the layer underneath. It works the same in every Python implementation. If you want the outer function to expose cache controls directly, you can forward them yourself:
import functools
from functools import cache
def passthrough(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
wrapper.cache_info = func.cache_info
wrapper.cache_clear = func.cache_clear
return wrapper
@passthrough
@cache
def cube(n):
return n ** 3
cube(2)
print(cube.cache_info())This forwarding only makes sense for decorators that are always applied on top of a cache. Otherwise func.cache_info raises AttributeError at decoration time.
A decorator with optional arguments, built with partial
partial solves a common decorator-writing problem. You want @log_calls and @log_calls(prefix="->") to both work. When the decorator is used with parentheses, Python calls it with only the options. It must return a decorator. partial can return that decorator by pre-filling the options.
import functools
from functools import cache, partial
def log_calls(func=None, *, prefix="calling"):
if func is None:
return partial(log_calls, prefix=prefix)
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"{prefix} {func.__name__}{args}")
return func(*args, **kwargs)
return wrapper
@log_calls
def hello():
return "hi"
@log_calls(prefix="->")
@cache
def slow_square(n):
return n * n
hello()
slow_square(3)
slow_square(3)
print(slow_square.__name__)The output is:
calling hello()
-> slow_square(3,)
-> slow_square(3,)
slow_squareWhen you write @log_calls(prefix="->"), the call returns partial(log_calls, prefix="->"). Python then applies that object to slow_square, which calls log_calls(slow_square, prefix="->") and takes the second branch. The * in the signature makes prefix keyword-only. That prevents a call like log_calls("->") from silently treating a string as the function.
This one example uses all three tools: partial builds the decorator, wraps preserves the name, and cache memoizes the work underneath.
Caching a partial, and partial-ing a cache
You can pre-fill arguments of a cached function with partial. Cache keys are built from the arguments exactly as the cached function receives them, so the way partial passes them matters.
from functools import cache, partial
@cache
def power(base, exponent):
print(f"computing {base}**{exponent}")
return base ** exponent
square = partial(power, exponent=2)
print(square(5))
print(square(5))
print(power(5, 2))
print(power.cache_info())The output is:
computing 5**2
25
25
computing 5**2
25
CacheInfo(hits=1, misses=2, maxsize=None, currsize=2)square(5) calls power(5, exponent=2). The direct call power(5, 2) passes the second value positionally. The cache treats these as different keys, so the work is done twice. Calls that mean the same thing but are spelled differently each get their own entry. This wastes memory and misses hits. To avoid it, choose one calling style for each cached function and use it everywhere. That includes any partial objects built on top of it.
The reverse direction also works. You can cache a partial by wrapping it, for example lru_cache(maxsize=128)(partial(power, exponent=2)). Two details to keep in mind:
- A
partialobject has no__name__. A decorator that readsfunc.__name__, likelog_callsabove, raisesAttributeErrorwhen given one. Usegetattr(func, "__name__", repr(func))if your decorator may receive partial objects. - The pre-filled arguments live in the partial object and are not part of the cache key. They are fixed for the life of that cache, which is what you want.
Combining the pitfalls
Each pitfall from earlier chapters can reappear in a stack, and some are easier to miss there.
- Unhashable arguments. The cache raises
TypeErrorfor a list, even when a logging layer above it handled the call without complaint. The log line prints first, and then the error appears. Convert to a tuple before the call, or add a small decorator above the cache that does the conversion. - Impure functions. A decorator that adds a timestamp or reads a global changes results without changing arguments. If the decorator sits inside the cache, those changes are frozen into the stored value. If it sits outside, they are applied fresh on every call.
- Unbounded growth.
@cachehas no limit. In a long-running service, preferlru_cache(maxsize=...)and monitorcache_info()through__wrapped__if another decorator sits on top. - Instance methods. Caching a method includes
selfin the key. The cache then holds a reference to every instance it has seen, and those instances cannot be garbage collected. The same stacking rules apply, but the leak is harder to see.
A checklist for stacking
- Decide what each layer must observe, then choose the order. Layers that must see every call go outside the cache.
- Always use
wrapsin your own decorators, so names and docstrings survive and__wrapped__is set. - Do not expect
cache_infoorcache_clearon anything except the cache layer itself. Use__wrapped__or forward them explicitly. - Keep one calling style for each cached function, so equivalent calls share a cache entry.
- Use
partialfor pre-filling, and for decorators that take options.
Exercise
You write @cache above @log_calls on a function and call it three times with the same argument. How many log lines are printed, and why? What changes if you swap the two decorators?
Show answer
One log line is printed. The cache is the outer layer, so the second and third calls are answered from memory without reaching the logging wrapper. If you swap them so that @log_calls is on top, the logging wrapper runs on every call and prints three lines, while the underlying function still runs only once.
Exercise
Given @cache def power(base, exponent) and square = partial(power, exponent=2), you call square(3) and then power(3, 2). What does power.cache_info() report for misses, and how would you change the code so the second call is a hit?
Show answer
It reports misses=2 and currsize=2. The first call stores the key for (3, exponent=2), and the second stores a key for (3, 2), because positional and keyword forms are different keys. To get a hit, call power the same way everywhere, for example power(3, exponent=2), or define square as partial(power, 3)-style calls consistently with positional arguments only.
Exercise
Write the first lines of a decorator retry(func=None, *, times=3) that works both as @retry and as @retry(times=5), using partial. Which functools function should decorate the inner wrapper, and why?
Show answer
Start with def retry(func=None, *, times=3): followed by if func is None: return partial(retry, times=times). The inner wrapper is decorated with functools.wraps(func), so the decorated function keeps its __name__ and __doc__ and exposes __wrapped__.