Sub topic 7
Avoiding repeated work with lru_cache
This chapter assumes you can read cProfile output and have already fixed the algorithm and data structure. Caching is the next step when a profile shows the same function called many times with the same arguments.
The idea: trade memory for time
A cache stores a result keyed by the arguments that produced it. The next call with the same arguments returns the stored result without running the function body again. This only helps when the function is called repeatedly with the same inputs, and when the same inputs always give the same output.
functools.lru_cache is a decorator that adds this behavior. "LRU" means least recently used. When the cache is full, the entry that was used longest ago is dropped.
A worked example
A naive recursive Fibonacci function recomputes the same values again and again. The number of calls grows exponentially. A cache turns that into a linear number of calls.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(80))
print(fib.cache_info())The first line prints the 80th Fibonacci number. The second prints a CacheInfo tuple with hits, misses, maxsize, and currsize. Here there are 81 misses, one for each value from 0 to 80, and 78 hits. A hit is a call answered from the cache. A miss is a call that had to run the function.
Without the decorator, fib(80) would take far longer than you would want to wait.
Choosing maxsize
The maxsize argument sets how many results the cache keeps.
| Setting | Behavior | Use when |
|---|---|---|
| `maxsize=None` | Unbounded, never evicts | The set of possible arguments is small and known |
| `maxsize=128` (default) | Evicts least recently used | A general default |
| `maxsize=N` | Evicts least recently used above N | You need to bound memory |
An unbounded cache on a function that receives many distinct arguments is a memory leak. Pick a bound when the input space is large.
Common errors
Check these before you add @lru_cache to a function.
- Unhashable arguments. Arguments become dictionary keys, so they must be hashable. Passing a list or dict raises
TypeError: unhashable type. Convert to a tuple or frozenset first. - Impure functions. If the result depends on the clock, a file, a database, or a random number, the cache returns stale answers. Cache only functions whose output depends solely on their arguments.
- Mutable return values. Every hit returns the same object. If the caller modifies a returned list, later callers see the change. Return tuples or copies.
- Methods. On an instance method,
selfbecomes part of the key. The cache then holds a reference to every instance, so those instances are never freed. - Caching cheap functions. A cache lookup has a cost. If the function is already fast, the cache can make it slower.
Verify the gain
Treat caching like any other change: measure before and after. Use cache_info() to see the hit ratio. A cache with few hits is not helping, and you should remove it. Then re-run your timing or profile to confirm the end-to-end speedup.
Exercise
You add @lru_cache(maxsize=None) to a function that takes a user ID and returns that user's current account balance from a database. Tests pass, but users later report outdated balances. Why, and what would you change?
Show answer
The function is not pure. Its result depends on database state, not only on the user ID, so the cache keeps returning the first balance it saw. Remove the cache from this function, or cache only stable data such as user profile fields that rarely change. If some staleness is acceptable, use a cache with an expiry time instead.
Exercise
After running a workload, fib.cache_info() shows hits=0, misses=5000, currsize=5000. What does this tell you about the cache, and what should you do?
Show answer
Every call used a different argument, so the cache never answered a call. It adds lookup cost and uses memory for no benefit. Remove the decorator, or restructure the code so that repeated work shares arguments.