Sub topic 9
Bounding memory with lru_cache
This chapter assumes you know how functools.cache works and that cache keys must be hashable. It covers lru_cache, which limits how many results are stored.
The problem with an unbounded cache
cache never discards anything. If a function is called with millions of distinct arguments, such as user IDs or file paths in a long-running service, the cache grows until the process runs out of memory.
functools.lru_cache fixes this with a size limit. When the cache is full, it discards the entry that was used least recently. LRU stands for "least recently used".
Using lru_cache with maxsize
Pass maxsize to set how many results to keep.
from functools import lru_cache
@lru_cache(maxsize=2)
def square(n):
print(f"computing {n}")
return n * n
square(1)
square(2)
square(1) # cache hit
square(3) # evicts the least recently used entry, 2
square(2) # computed again
print(square.cache_info()) # CacheInfo(hits=1, misses=4, maxsize=2, currsize=2)
square.cache_clear()
print(square.cache_info()) # CacheInfo(hits=0, misses=0, maxsize=2, currsize=0)The trace is worth following step by step, because the eviction order is the whole point.
square(1)andsquare(2)are misses. The cache now holds 1 and 2.square(1)is a hit. It makes 1 the most recently used entry, so 2 is now the oldest.square(3)is a miss and the cache is full, so entry 2 is evicted. The cache holds 1 and 3.square(2)is a miss again. It evicts 1, which is now the oldest.
The result is 1 hit and 4 misses. A hit refreshes an entry's age, so entries that are used often stay in the cache.
Choosing a maxsize
The default is maxsize=128. You can write @lru_cache with no parentheses to get that default, or @lru_cache(), which is equivalent. Both forms work in Python 3.8 and later.
| Setting | Behavior |
|---|---|
| `maxsize=128` (default) | Keeps the 128 most recently used results |
| `maxsize=N` | Keeps the N most recently used results |
| `maxsize=None` | No limit, which is what `cache` does |
| `maxsize=0` | Stores nothing, but still counts calls |
To pick a number, estimate how many distinct argument combinations are "hot", meaning called repeatedly in a short period. Set maxsize somewhat above that. Then check cache_info() under realistic load. A low hit count with currsize stuck at maxsize means the cache is too small for the workload. Few misses and a currsize far below maxsize means you can reduce it.
The typed parameter
By default, 1 and 1.0 compare equal and hash the same, so they share one cache entry. Set typed=True to cache them separately by type.
from functools import lru_cache
@lru_cache(maxsize=None, typed=True)
def describe(x):
return f"{type(x).__name__}: {x}"
print(describe(1)) # int: 1
print(describe(1.0)) # float: 1.0
print(describe.cache_info().currsize) # 2Without typed=True, the second call would return the cached int: 1 result. That is a real bug when the output depends on the type.
How lru_cache keys its entries
The key is built from the positional and keyword arguments. This has two consequences you should know.
f(1, 2)andf(a=1, b=2)are cached as separate entries, even though the function treats them the same.- Every argument must be hashable, as with
cache. Passing a list raisesTypeError.
Summary of the trade-off
Use cache when the set of possible arguments is small and known, such as the recursive Fibonacci example. Use lru_cache(maxsize=N) when the arguments come from an open-ended source and memory must stay predictable. The cost of the bound is that evicted results must be recomputed.
Exercise
A function decorated with @lru_cache(maxsize=3) is called with the arguments 1, 2, 3, 1, 4, 2, in that order. Which calls are cache hits, and what is the final currsize?
Show answer
Only the fourth call, 1, is a hit. Calls 1, 2 and 3 are misses that fill the cache. The call with 1 is a hit and makes 2 the oldest entry. The call with 4 is a miss and evicts 2. The call with 2 is then a miss again, and it evicts 3. That gives 1 hit and 5 misses. The final currsize is 3, because the cache never holds more than maxsize entries.