Sub topic 8
Memoizing with cache
This chapter assumes you can write Python functions, use the @ decorator syntax, and tell hashable types (tuple, str, int) from unhashable ones (list, dict, set). It builds on the earlier chapter on why caching function results helps.
What cache does
functools.cache is a decorator that memoizes a function. Each time you call the function, cache builds a key from the arguments. If the key is already stored, it returns the saved result. If not, it runs the function, stores the result, and returns it.
cache was added in Python 3.9. It has no size limit, so it never evicts an entry. The next chapter covers lru_cache, which does.
A worked example: Fibonacci
A recursive Fibonacci function repeats the same work many times. fib(5) calls fib(4) and fib(3), and fib(4) calls fib(3) again. The number of calls grows exponentially with n.
With @cache, each value is computed once:
from functools import cache
@cache
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(80)) # 23416728348467685
print(fib.cache_info()) # CacheInfo(hits=78, misses=81, maxsize=None, currsize=81)The recursive calls inside fib go through the decorated name, so they hit the cache too. The result is 81 misses (one for each of fib(0) through fib(80)) and 78 hits. Without the cache, fib(80) would take far too long to finish.
The flow for each call looks like this:
What counts as the same call
The key is built from the arguments, so the arguments must be hashable. Two calls share a cache entry only if their arguments compare equal and hash equally. Keep these details in mind:
f(1, 2)andf(a=1, b=2)can be stored as separate entries, because the key records how the arguments were passed.f(1)andf(1.0)share an entry, because1 == 1.0and their hashes match. The first result stored is the one returned.- The cache holds references to the arguments and to the results. Neither can be garbage collected while it sits in the cache.
Arguments must be hashable
Lists, dicts, and sets cannot be hashed, so passing one raises a TypeError. Convert such arguments to a tuple or frozenset before the call:
from functools import cache
@cache
def total(items):
return sum(items)
# total([1, 2, 3]) raises TypeError: unhashable type: 'list'
print(total((1, 2, 3))) # 6Only cache pure functions
A pure function returns the same result for the same arguments and has no side effects. Caching suits such functions. It breaks functions that:
- read the clock, random numbers, files, or a database, because the result can change between calls;
- print, write, or modify something, because those side effects run only on the first call;
- return a mutable object, because every caller receives the same object, and a change made by one caller shows up for all of them.
The second point is easy to miss. The print in this function runs once, even though it is called twice:
from functools import cache
@cache
def load(name):
print(f"loading {name}")
return name.upper()
print(load("data")) # prints "loading data", then DATA
print(load("data")) # prints only DATAThe cache grows without limit
Because cache never evicts, a function called with many distinct arguments keeps every result in memory. In a long-running program such as a web server, this can use more and more memory. If the number of distinct arguments is large or unknown, use a bounded cache instead.
Reading and clearing the cache
A cached function gains two methods. cache_info() reports hits, misses, and current size. cache_clear() empties the cache and resets the counters. Use them to check that the cache is working, and to reset it in tests.
from functools import cache
@cache
def square(n):
return n * n
square(3)
square(3)
print(square.cache_info()) # CacheInfo(hits=1, misses=1, maxsize=None, currsize=1)
square.cache_clear()
print(square.cache_info()) # CacheInfo(hits=0, misses=0, maxsize=None, currsize=0)Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `TypeError: unhashable type` | A list, dict, or set was passed | Pass a tuple or frozenset |
| A function returns outdated values | The function is not pure | Remove the cache or call `cache_clear()` |
| Memory keeps growing | Unbounded cache and many distinct arguments | Use `lru_cache(maxsize=...)` |
| A side effect happens only once | The cache skips the function body on hits | Keep side effects outside the cached function |
Exercise
You decorate a function with @cache and call it as f(2), then f(2), then f(3). What does cache_info() report for hits, misses, and currsize?
Show answer
hits=1, misses=2, currsize=2. The first f(2) is a miss and is stored. The second f(2) is a hit. The call f(3) is a new key, so it is a miss and the cache then holds two entries.
Exercise
A function decorated with @cache takes a list of numbers and raises TypeError. What are two ways to fix it?
Show answer
Lists are unhashable, so they cannot form a cache key. Either pass a tuple, for example total((1, 2, 3)), or convert the list inside a small wrapper function before calling the cached function, for example total(tuple(items)).