Sub topic 7
Avoiding repeated work with lru_cache
The previous chapters fixed algorithms and data structures. Some programs still call the same function with the same arguments many times. Caching (also called memoization) stores a result the first time you compute it and returns the stored copy afterward. Python's functools.lru_cache does this with one decorator.
This chapter assumes you can read a cProfile report and know what a decorator is. It also assumes you know that dict keys must be hashable. Caching is worth trying when the profile shows one function with a high call count and the same arguments recurring.
How lru_cache works
lru_cache wraps a function and keeps a dictionary that maps the call's arguments to its return value. On each call it builds a key from the arguments and looks it up.
- On a hit, the stored value is returned and the function body does not run.
- On a miss, the function runs, the result is stored, and the result is returned.
LRU stands for "least recently used". When you set a size limit and the cache is full, the entry that has gone unused the longest is evicted.
The classic example: Fibonacci
The naive recursive Fibonacci recomputes the same values over and over. fib(n) calls fib(n - 1) and fib(n - 2), so the number of calls grows exponentially. Caching removes the repeats.
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())This prints 23416728348467685 and then CacheInfo(hits=78, misses=81, maxsize=None, currsize=81). Each of the 81 values from fib(0) to fib(80) is computed once, which is why there are 81 misses. The 78 hits are the second recursive calls, which find a value that was already stored. The uncached version would take far longer than you would want to wait for fib(80).
cache_info() is your main tool for checking that a cache helps. A cache with almost no hits only adds overhead.
Measuring the benefit
Do not assume a cache is faster. Time it, using the techniques from the earlier chapters. The next script simulates an expensive pure computation and times a cold call and a warm call.
import time
from functools import lru_cache
@lru_cache(maxsize=128)
def expensive(n):
total = 0
for i in range(2_000_000):
total += (i * n) % 7
return total
def timed(label, func, *args):
start = time.perf_counter()
result = func(*args)
elapsed = time.perf_counter() - start
print(f"{label}: {elapsed:.6f}s")
return result
first = timed("cold call", expensive, 3)
second = timed("warm call", expensive, 3)
assert first == second
print(expensive.cache_info())The cold call pays for the loop. The warm call is only a dictionary lookup, so it should be many orders of magnitude faster. The last line shows hits=1, misses=1.
Choosing maxsize
The maxsize argument controls memory use.
| Setting | Behavior | Use when |
|---|---|---|
| `maxsize=128` (default) | Keeps the 128 most recently used results | You don't know the input range yet |
| `maxsize=N` | Keeps the N most recently used results | The set of hot inputs is bounded and known |
| `maxsize=None` | Never evicts, no size limit | The set of possible inputs is small and finite |
| `maxsize=0` | Stores nothing | Almost never useful |
Python 3.9 added functools.cache, which is the same as lru_cache(maxsize=None) and reads more clearly.
The eviction order is easy to check with a tiny cache.
from functools import lru_cache
@lru_cache(maxsize=2)
def square(n):
return n * n
square(1) # miss
square(2) # miss
square(1) # hit, so 1 is now the most recently used
square(3) # miss, evicts 2 (the least recently used)
square(2) # miss again, because 2 was evicted
print(square.cache_info())The output is CacheInfo(hits=1, misses=4, maxsize=2, currsize=2).
An unbounded cache on a function whose inputs keep changing is a memory leak. Examples are request IDs, timestamps, or user-supplied strings. If the profile shows memory growing, tracemalloc from the previous chapter will point at the cache. Switch to a bounded maxsize.
When a cache is safe
A cached function must be pure for the cache to be correct. Its return value must depend only on its arguments, and calling it must not need side effects. Check these conditions before you add the decorator.
- The result depends only on the arguments. A function that reads a file, a database row, the clock, or a random number will keep returning the first answer. The cache hides all later changes.
- The arguments are hashable. The cache key is built from the arguments, so lists, dicts, and sets raise
TypeError. - The function has no required side effects. A hit skips the body. A logging or counter update inside the function stops happening.
- The result is not mutated by callers. The cache returns the same object every time, not a copy.
Unhashable arguments
Passing a list fails immediately.
from functools import lru_cache
@lru_cache(maxsize=None)
def total(values):
return sum(values)
try:
total([1, 2, 3])
except TypeError as exc:
print(exc) # unhashable type: 'list'
print(total((1, 2, 3))) # 6The usual fix is to convert at the call site, as above, using tuple(...) for sequences and frozenset(...) for sets. For large inputs, converting on every call costs time too, so check that the total is still a win.
Shared mutable results
Because a hit returns the stored object itself, mutating it changes the cache.
from functools import lru_cache
@lru_cache(maxsize=None)
def make_row(n):
return [0] * n
row = make_row(3)
row.append(99)
print(make_row(3)) # [0, 0, 0, 99], the cached list was changedReturn immutable values (tuples, numbers, strings, frozensets), or copy the result before you change it.
Equal arguments that look different
The key is built from how you call the function, not only from the values. f(1, 2) and f(a=1, b=2) are separate entries, and so are f(1, b=2) and f(b=2, a=1) in some forms. Use one calling style for a cached function. By default 1 and 1.0 hash equal and share an entry. Pass typed=True to keep them apart.
Caching methods
Putting @lru_cache on a method includes self in the key. That causes two problems. The cache holds a reference to every instance it has seen, so those instances are never garbage collected while their entries remain. The instance must also be hashable, and a class that defines __eq__ without __hash__ is not.
For a value that is computed once per instance, use functools.cached_property. It stores the result in the instance's own __dict__, so it is freed together with the instance.
from functools import cached_property
class Report:
def __init__(self, numbers):
self.numbers = numbers
@cached_property
def total(self):
print("computing")
return sum(self.numbers)
report = Report([1, 2, 3])
print(report.total) # prints "computing", then 6
print(report.total) # prints 6 onlyIf the work does not really depend on instance state, move it into a module-level function and cache that.
Managing the cache
The wrapped function has two helper methods.
cache_info()returns hits, misses,maxsize, andcurrsize.cache_clear()empties the cache and resets the counters.
Call cache_clear() when the underlying data changes, and in tests, so one test's cached values do not leak into the next. The cache is safe to use from several threads. Two threads that miss on the same key at the same moment may both run the function, though, so a cached function should be idempotent.
Also remember that each process has its own cache. With multiprocessing, as in the concurrency chapter, workers do not share entries.
Common mistakes
- Caching a function that is already fast. Key building and lookup cost something. For a trivial function, a cache can be slower than recomputing.
- Caching with a low hit rate. If
missesis close to the total number of calls, the cache only spends memory. - Caching a time-dependent or I/O-dependent function. The cache returns stale results with no error.
- Choosing the wrong layer. If a loop calls a function with the same argument each time, hoisting the call out of the loop may fix the problem with no cache at all.
Exercise
A function load_rate(currency) reads an exchange rate from a web API and is decorated with @lru_cache(maxsize=None). After a day the program still returns the rate from the first call, and memory use has grown. Name two problems with this design and one fix for each.
Show answer
First, the function is not pure. Its result depends on data outside its arguments, so the cache returns a stale rate forever. Fix it by calling load_rate.cache_clear() on a schedule, or by caching with a time-to-live (for example, add a time bucket such as int(time.time() // 300) as an extra argument). Second, maxsize=None never evicts entries, so any growth in distinct arguments grows memory without limit. Fix it by setting a finite maxsize, or by confirming the set of currencies is small and fixed. Check the effect with cache_info() and tracemalloc.
Exercise
You add @lru_cache(maxsize=None) to a function and cache_info() reports hits=2, misses=9998. What does this tell you, and what should you do?
Show answer
Almost every call used arguments that had not been seen before, so the cache is not avoiding work. It adds key-building overhead and stores 9,998 results that are never reused. Remove the decorator, or find why the arguments vary (for example, a timestamp passed in) and normalize them. If the same work really is repeated at a higher level, restructure the code or cache at that level instead.