Sub topic 7
Why cache function results
This chapter explains the idea behind functools.cache and functools.lru_cache before you use them. You will see the problem caching solves, write a small cache by hand, and learn which functions are safe to cache. The next chapter introduces functools.cache itself.
I assume you can write functions with keyword arguments and use the @ decorator syntax. I also assume you know that a tuple is hashable and a list is not.
The cost of recomputing
A function call does work every time you make it, even when you pass the same arguments as last time. Most of the time that is fine. It becomes a problem in two situations:
- The function is expensive, for example it parses a large file, queries a database, or does heavy arithmetic.
- The function is cheap, but it is called a huge number of times with a small set of distinct arguments.
Recursive Fibonacci is the classic second case. This version counts how many times its body runs:
calls = 0
def fib(n):
global calls
calls += 1
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(25)) # 75025
print(calls) # 242785Computing fib(25) runs the body 242,785 times, although only 26 distinct values are involved (fib(0) through fib(25)). The call fib(23) alone happens inside both fib(24) and fib(25), and each of those repeats its own subtree. The number of calls grows exponentially with n, so fib(35) takes noticeable time and fib(80) would never finish.
The fix is to remember each answer the first time you compute it.
What memoization is
Memoization is a technique where a function stores its results, keyed by its arguments, and returns the stored result when it sees the same arguments again. The name comes from "memo": the function writes itself a note.
The working model has three parts:
- A lookup table, usually a dictionary, that maps an argument key to a result.
- A check on every call: is this key already in the table?
- On a miss, run the real function and store the result. On a hit, return the stored result without running the function.
A hit costs one dictionary lookup. A miss costs the original work plus a small amount of bookkeeping. Memoization pays off when hits are common and the original work is much more expensive than a lookup.
A hand-written memoizer
You already know decorators, so a memoizer is a short one. This version is deliberately minimal:
def memoize(func):
results = {}
def wrapper(*args):
if args not in results:
results[args] = func(*args)
return results[args]
return wrapperThe results dictionary lives in the closure, so each decorated function gets its own table. The tuple args is the key. This sketch skips functools.wraps so the caching logic stays visible. A real decorator should use it, as you saw earlier in this tutorial.
Apply it to Fibonacci:
calls = 0
@memoize
def fib(n):
global calls
calls += 1
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(25)) # 75025
print(calls) # 26The body now runs 26 times instead of 242,785. The recursive calls inside fib look up the global name fib, which is now the wrapper. So every recursive call also goes through the cache. This is why the decorator syntax works so well for recursion: the cache covers the inner calls without any change to the function body.
Measuring the win on an expensive function
Here is the other case, a single slow function called repeatedly with the same input:
import time
def memoize(func):
results = {}
def wrapper(*args):
if args not in results:
results[args] = func(*args)
return results[args]
return wrapper
def slow_square(n):
time.sleep(0.5) # stands in for real work
return n * n
cached_square = memoize(slow_square)
for attempt in (1, 2):
start = time.perf_counter()
result = cached_square(12)
elapsed = time.perf_counter() - start
print(f"attempt {attempt}: {result} in {elapsed:.3f}s")The first attempt takes about half a second. The second takes a few microseconds, because it never reaches time.sleep. The exact numbers depend on your machine, but the gap between them will be large.
Limits of this hand-written version
The sketch is enough to show the idea, but it has gaps that explain why the standard library provides a better tool:
- It accepts only positional arguments.
cached_square(n=12)raisesTypeError, becausewrapperhas no**kwargs. Supporting keywords means building a key that includes them, and then deciding whetherf(1, 2)andf(a=1, b=2)count as the same call. - The table grows without limit. Every new argument tuple adds an entry that is never removed.
- It is not designed for threads. Two threads can miss on the same key at the same time and both run the function.
- It offers no way to see hit rates or to clear the table.
functools.cache and functools.lru_cache handle these concerns for you. The following chapters cover them.
When a function is safe to cache
Memoization assumes that the same arguments always produce the same result. A function with that property is called pure. For a pure function, returning a stored answer is indistinguishable from recomputing it, apart from speed.
A function is safe to cache when all of these hold:
- Its result depends only on its arguments.
- It has no side effects you need on every call, such as printing, writing a file, or sending a request.
- Its arguments are hashable, so they can be used as a dictionary key.
- It does not return a mutable object that callers will modify.
The table below shows how common functions fare.
| Function | Safe to cache? | Reason |
|---|---|---|
| `fib(n)` | Yes | Result depends only on `n`. |
| Parsing a fixed config string into a dict | Yes, with care | Pure, but see the mutable result warning below. |
| `random.randint(1, 6)` wrapper | No | Same arguments must give different results. |
| `datetime.now()` wrapper | No | Result depends on the clock. |
| `send_email(to, body)` | No | The side effect must happen every time. |
| `convert(amount)` that reads a global rate | No | Hidden input outside the arguments. |
Hidden inputs produce stale answers
The most common mistake is caching a function that reads state from outside its arguments. The cache cannot see that state change, so it keeps returning the old answer:
def memoize(func):
results = {}
def wrapper(*args):
if args not in results:
results[args] = func(*args)
return results[args]
return wrapper
rate = 2
def convert(amount):
return amount * rate
cached_convert = memoize(convert)
print(cached_convert(100)) # 200
rate = 3
print(convert(100)) # 300
print(cached_convert(100)) # 200, staleNo error is raised, and the wrong value looks plausible. These bugs are hard to spot because the program keeps running. The fix is to make hidden inputs explicit. Here, rate becomes a second parameter, so a new rate produces a new cache key.
Mutable results are shared
On a hit, the cache returns the same object it stored, not a copy. If the function returns a list or dict and a caller modifies it, every later caller sees the modification:
def memoize(func):
results = {}
def wrapper(*args):
if args not in results:
results[args] = func(*args)
return results[args]
return wrapper
@memoize
def default_tags(kind):
return ["new", kind]
first = default_tags("post")
first.append("oops")
print(default_tags("post")) # ['new', 'post', 'oops']The second call did not rebuild the list. It returned the one the first caller had already changed. If you cache a function like this, return an immutable value such as a tuple, or treat the result as read-only.
Unhashable arguments
The cache key is built from the arguments, and dictionary keys must be hashable. Passing a list fails immediately:
def memoize(func):
results = {}
def wrapper(*args):
if args not in results:
results[args] = func(*args)
return results[args]
return wrapper
@memoize
def total(items):
return sum(items)
print(total((1, 2, 3))) # 6
try:
total([1, 2, 3])
except TypeError as exc:
print(exc) # unhashable type: 'list'The error comes from the args not in results check, because a tuple containing a list cannot be hashed. The usual remedy is to convert the argument to a tuple at the call site.
The costs of caching
Memoization trades memory for time. Before adding it, weigh these costs:
- Memory. Each distinct argument set keeps its result alive. A function called with millions of different inputs fills memory with entries that will never be hit again. This is the reason bounded caches exist.
- Lookup overhead. A cheap function, such as one that adds two numbers, can be slower with a cache than without. Building the key and hashing it costs more than the work being skipped.
- Stale data. Anything that changes outside the arguments invalidates old entries, as the
rateexample showed. - Lifetime. Cached results can keep large objects, or the arguments themselves, alive longer than you expect. Arguments stored in keys cannot be garbage collected while the entry exists.
A good candidate for caching has three traits: the work is expensive or repeated heavily, the set of distinct inputs is small or has a clear working set, and the function is pure. If any trait is missing, measure before you cache.
Where this leads
You now have the model: a table keyed by arguments, a hit path that skips the work, and a miss path that fills the table. The two standard-library tools differ in how they manage the table's size:
functools.cachekeeps every result forever. It is simple and fast, and it suits functions with a small, bounded set of inputs, likefib.functools.lru_cachecan limit the table tomaxsizeentries and discards the least recently used one when it is full. It suits functions with many possible inputs.
Both are decorators, both require hashable arguments, and both inherit every purity rule in this chapter.
Exercise
Your teammate decorates def get_price(item_id) with a memoizer. The function reads the current price from a database, and prices change during the day. Users start seeing yesterday's prices. Explain why it happens and give two ways to fix it.
Show answer
The function is not pure. Its result depends on database state, which is a hidden input that the cache key (item_id) cannot see. After the first call for an item, the memoizer returns the stored price and never queries the database again. Fixes: (1) do not cache this function, and cache only the stable parts of the work; (2) make the changing input part of the arguments, for example pass a version or a timestamp rounded to a time bucket such as the current hour, so a new bucket creates a new key and old entries stop being hit. Another option is a cache with expiry, which functools does not provide.
Exercise
Using the memoize decorator from this chapter, fib(30) is called once. How many times does the body of fib run, and why is it not 30?
Show answer
It runs 31 times. The distinct arguments are 0 through 30, which is 31 values, and each is computed exactly once on its first miss. Every later request for the same n, including the ones made by the recursive calls inside fib, is a hit and skips the body.