Memoization in Python with lru_cache
This article explains how functools.cache and functools.lru_cache store the results of a function, how the LRU policy evicts entries, and which functions, arguments and methods must not be cached.
A function that receives the same arguments many times and computes the same result every time wastes exactly the work that a memory of earlier answers would save. This technique, known as memoization, stores each result under the arguments that produced it and returns the stored value on later calls. The module functools provides it as a decorator in two forms, lru_cache and, since Python 3.9, cache. The present article examines how both decorators work, how a bounded cache decides which entries to discard, how its statistics are inspected, and which kinds of functions must not be cached. A cache placed in front of a pure and expensive function is the secret weapon that turns repeated work into a dictionary lookup.
Memoization with functools.cache
The recursive definition of the Fibonacci sequence is the classic example of repeated work: computing fib(25) requires fib(24) and fib(23), but fib(24) computes fib(23) again, and the duplication grows exponentially with n. The following example counts the calls of the plain version and compares it with the cached one.
import timeit
from functools import cache
calls = 0
def fib(n):
global calls
calls += 1
return n if n < 2 else fib(n - 1) + fib(n - 2)
@cache
def fib_cached(n):
return n if n < 2 else fib_cached(n - 1) + fib_cached(n - 2)
print(fib(25), calls) # Output: 75025 242785
print(fib_cached(25)) # Output: 75025
print(fib_cached.cache_info()) # Output: CacheInfo(hits=23, misses=26, maxsize=None, currsize=26)
naive = timeit.timeit(lambda: fib(25), number=5) / 5
cached = timeit.timeit(lambda: (fib_cached.cache_clear(), fib_cached(25)), number=5) / 5
print(naive > 100 * cached) # Output: True
The plain function performs 242,785 calls to compute a single value, while the cached one performs only 26 real computations, one for each value from 0 to 25, and answers the other 23 requests from the cache. On the test machine, with CPython 3.12, the plain version took about 6 milliseconds and the cached version, starting from an empty cache, about 5 microseconds. Times of this size must be measured with timeit or time.perf_counter(), since time.time() lacks the resolution and reports zero for the fast case. The decorator syntax follows the mechanism examined in the article devoted to decorators: cache returns a wrapper that builds a key from the arguments, looks it up in a dictionary and calls the original function only on a miss.
Limited Bag Slots: How the LRU Policy Evicts Entries
The decorator cache never discards anything, so its memory grows with every new argument. lru_cache adds a limit, maxsize, which is 128 by default: when the cache is full, the entry that was used least recently (LRU) is discarded to make room for the new one. Since Python 3.8 the decorator can be applied without parentheses, and lru_cache(maxsize=None) is equivalent to cache, which is smaller and faster because it never needs to track the order of use.
from functools import lru_cache
@lru_cache(maxsize=2)
def square(x):
print("computing", x)
return x * x
for value in (1, 2, 1, 3, 2):
square(value)
# Output: computing 1
# Output: computing 2
# Output: computing 3
# Output: computing 2
print(square.cache_info()) # Output: CacheInfo(hits=1, misses=4, maxsize=2, currsize=2)
print(square.cache_parameters()) # Output: {'maxsize': 2, 'typed': False}
The second call with 1 is a hit, and it makes 1 the most recently used entry. When 3 arrives, the cache is full and the least recently used entry is 2, which is discarded; the last call with 2 must therefore compute it again. The method cache_info() reports hits, misses and the current size, which is the measurement that justifies a cache, and cache_clear() empties it, for example when the data behind the function changes.
What the Cache Remembers
A cached function returns the stored object itself, not a copy, and its key is built from the arguments exactly as they were passed. Both details have consequences that the following example reproduces.
from functools import cache, lru_cache
@cache
def default_tags():
return ["python"]
default_tags().append("draft")
print(default_tags()) # Output: ['python', 'draft']
@lru_cache
def add(a, b):
return a + b
add(a=1, b=2); add(b=2, a=1); add(1, 2)
print(add.cache_info().misses) # Output: 3
print(add(1.0, 2.0)) # Output: 3
try:
add([1], [2])
except TypeError as error:
print(error) # Output: unhashable type: 'list'
The list returned by default_tags is shared by every caller, so one caller's modification is seen by the next. The same sum is stored three times, because positional and keyword forms, and different keyword orders, produce different keys. The call add(1.0, 2.0) returns the integer 3 instead of the float 3.0, because the key (1.0, 2.0) is equal to (1, 2) and has the same hash, so the floats find the entry stored for the integers; the parameter typed=True keeps arguments of different types in separate entries. Finally, every argument must be hashable, since the key is used in a dictionary.
Caching Methods
Applied to a method, lru_cache includes self in the key, and the cache, which belongs to the function and therefore to the class, keeps a reference to every instance it has seen. The following example shows that an instance survives its deletion for that reason.
import gc
import weakref
from functools import cached_property, lru_cache
class Report:
def __init__(self, rows):
self.rows = rows
@lru_cache
def total(self):
return sum(self.rows)
class LeanReport:
def __init__(self, rows):
self.rows = rows
@cached_property
def total(self):
return sum(self.rows)
report, lean = Report([1, 2, 3]), LeanReport([1, 2, 3])
print(report.total(), lean.total) # Output: 6 6
watchers = weakref.ref(report), weakref.ref(lean)
del report, lean
gc.collect()
print([ref() is not None for ref in watchers]) # Output: [True, False]
The instance of Report remains alive after del, held by the cache of total, while the instance of LeanReport is released, because cached_property stores the value in the instance itself, as described in the article devoted to descriptors. The weak references used to observe both objects are those examined in the article devoted to weak references.
Pitfalls of Memoization
A cache changes when a function runs and which objects stay in memory, and each pitfall comes from forgetting one of those effects. Six pitfalls are distinguished, which are the following:
- Impure functions. A function whose result depends on time, randomness, files or a database returns stale values once cached, and a function with side effects performs them only on the first call.
- Shared mutable results. Every caller receives the same object, so a modification by one caller corrupts the cache for the others.
- Unbounded growth.
cacheandlru_cache(maxsize=None)keep every argument and result forever; functions called with many distinct arguments need a boundedmaxsize. - Cached methods.
lru_cacheon a method keeps every instance alive;cached_property, or a cache keyed by a hashable identifier instead ofself, avoids it. - Equivalent keys. Keyword order creates duplicate entries, and equal values of different types share an entry unless
typed=True. - Recursion depth. A cache removes repeated work, not recursion: computing
fib_cached(5000)from an empty cache still raisesRecursionError, so deep values must be computed bottom-up or warmed up gradually.
Two further details complete the picture. The cache is thread-safe in the sense that its structure remains consistent, but the documentation warns that two threads may compute the same value concurrently before either result is stored. The cache also cannot share results between processes, since each process holds its own copy.
Choosing the Right Tool
Consequently, each form of caching suits a particular combination of purity, argument variety and object lifetime, as the following table summarizes.
| Situation | Recommended tool |
|---|---|
| Pure function, small and bounded set of arguments | functools.cache |
| Pure function, many distinct arguments over time | functools.lru_cache(maxsize=N) |
| Expensive value computed once per instance | functools.cached_property |
| Results that must expire after a time or on external changes | An explicit dictionary with expiry, or a dedicated caching library |
| Functions with side effects or random or time-dependent results | No cache |
| Results needed by several processes or machines | An external cache, not functools |
Conclusion
It is concluded that functools.cache and functools.lru_cache implement memoization as a dictionary placed in front of a function, which turns repeated computations into lookups and, in recursive problems such as the Fibonacci sequence, reduces hundreds of thousands of calls to a few dozen. This magic is safe only for pure functions with hashable arguments and immutable results, and its benefit must be confirmed with cache_info() and a measurement rather than assumed. Caching appears inside the interpreter as well: string interning, by which CPython reuses a single object for equal strings, is developed in a future article of this series.