Sub topic 8
Memoizing with cache
This chapter covers functools.cache, the decorator that stores a function's results so repeated calls with the same arguments skip the work. It assumes you can write and call Python functions with keyword arguments, that you know the @decorator syntax, and that you know which built-in types are hashable (a tuple is, a list is not). It also assumes you've read the earlier chapter on why caching helps.
What cache does
functools.cache was added in Python 3.9. You put it above a function:
from functools import cache
calls = 0
@cache
def slow_square(n):
global calls
calls += 1
return n * n
print(slow_square(4)) # 16
print(slow_square(4)) # 16, served from the cache
print(slow_square(5)) # 25
print(calls) # 2The function body ran twice, once for 4 and once for 5. The second call with 4 never entered the body.
Internally, cache wraps your function in an object that holds a dictionary. Each call builds a key from the arguments and looks it up. On a hit, it returns the stored value. On a miss, it calls your function, stores the result under the key, and returns it.
cache(func) is equivalent to lru_cache(maxsize=None)(func). It has no eviction logic and no size limit, which makes it slightly faster and simpler. The next chapter covers the bounded version.
Where memoization pays off: recursion
The classic case is a recursive function whose calls overlap. Naive Fibonacci recomputes the same values over and over, so its running time grows exponentially. Caching makes each value 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)Without the decorator, fib(80) would take far longer than you'd want to wait. With it, there are exactly 81 misses, one for each of fib(0) through fib(80). The 78 hits are the second recursive call at each level, which finds its value already stored.
Recursion inside the function refers to the global name fib. That name now points to the cached wrapper, so the recursive calls are cached too. This is why the decorator form works so well here.
How the cache key is built
The key comes from the arguments exactly as the caller wrote them. Three details follow from that.
Arguments must be hashable
The key is stored in a dictionary, so every argument must be hashable. Passing a list raises TypeError:
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))) # 6The usual fix is to convert at the call site, for example total(tuple(my_list)). The error appears at call time, not at decoration time.
The call form matters
Defaults are not filled in before the key is built, and keyword arguments are keyed separately from positional ones. These three calls mean the same thing to your function, but they create three entries:
from functools import cache
@cache
def add(a, b=0):
print("computing")
return a + b
add(1)
add(1, 0)
add(1, b=0)
print(add.cache_info()) # CacheInfo(hits=0, misses=3, maxsize=None, currsize=3)"computing" prints three times. Nothing breaks, since you only lose some cache efficiency, but it's worth being consistent about how you call a cached function. A single call form also keeps currsize meaningful.
Equal values share an entry
Keys are compared with ==, not by type. Since 2 == 2.0, a call with 2.0 can hit an entry created by a call with 2:
from functools import cache
@cache
def scale(x, factor):
return x * factor
print(scale(2, 3)) # 6
print(scale(2.0, 3)) # 6, not 6.0: the stored int result is returnedThe second call returns the integer stored by the first, not the float you might expect. lru_cache has a typed=True option that keeps such calls separate, but cache does not accept any options. If type distinctions matter, use lru_cache(maxsize=None, typed=True).
Only cache pure functions
A cache assumes the same arguments always produce the same result. That holds for a pure function, one that depends only on its arguments and has no side effects. It fails for functions that:
- read the clock, a random number generator, a file, a database, or a network response
- read global or instance state that changes
- need to print, log, or modify something on every call, because a hit skips the body entirely
import time
from functools import cache
@cache
def stamp(label):
return f"{label}@{time.time()}"
first = stamp("job")
time.sleep(0.01)
print(first == stamp("job")) # True: the "current" time is frozenThe function looks like it returns the current time, but every call after the first returns the original value. Nothing signals that the data has gone stale.
What gets stored
Exceptions are not cached
If the function raises, nothing is stored. The next call with the same arguments runs the function again:
from functools import cache
@cache
def risky(n):
print("trying", n)
if n < 0:
raise ValueError("negative")
return n
for _ in range(2):
try:
risky(-1)
except ValueError:
pass
# prints "trying -1" twiceReturn values are shared, not copied
The cache stores a reference to the returned object. If the function returns a mutable object and a caller modifies it, every later caller sees the change:
from functools import cache
@cache
def load_defaults():
return {"retries": 3}
settings = load_defaults()
settings["retries"] = 99
print(load_defaults()) # {'retries': 99}Return immutable values (tuples, strings, numbers, frozen dataclasses), or have callers copy the result before changing it.
Memory is never released
cache has no limit. Every distinct set of arguments adds an entry that lives until you clear the cache or the process exits. That is fine for fib, whose key space is small. It is a slow memory leak for a function that takes user IDs, file paths, or timestamps. For those, use the bounded lru_cache from the next chapter.
Inspecting and bypassing the cache
The wrapper returned by cache has a few extra attributes:
cache_info()returns hits, misses,maxsize(Nonehere), and the current number of entries.cache_clear()empties the cache and resets the counters.__wrapped__is the original, undecorated function.
from functools import cache
@cache
def cube(n):
print(f"computing {n}")
return n ** 3
cube(3)
cube(3)
print(cube.cache_info()) # CacheInfo(hits=1, misses=1, maxsize=None, currsize=1)
cube.__wrapped__(3) # prints "computing 3": bypasses the cache
print(cube.cache_info()) # unchanged: hits=1, misses=1, currsize=1
cube.cache_clear()
print(cube.cache_info()) # CacheInfo(hits=0, misses=0, maxsize=None, currsize=0)Calling __wrapped__ is handy in tests, because you can check the real computation without touching the cache. The cache_info and cache_clear attributes are covered in more detail in a later chapter.
Limits worth knowing
Deep recursion
Caching does not remove Python's recursion limit. A call such as fib(5000) still tries to nest thousands of calls deep before any value is stored, and it fails with RecursionError under the default limit. One workaround is to warm the cache with smaller values first, so each call only recurses a short distance:
from functools import cache
@cache
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
for i in range(0, 3001, 100):
fib(i)
print(fib(3000) % 1000) # last three digits of a very large integerThreads
The cache's internal bookkeeping is thread-safe, so concurrent calls will not corrupt it. However, the wrapper does not lock around your function. If two threads miss on the same key at the same moment, both may run the function. This matters only when the function is expensive or has side effects.
Methods
Decorating an instance method puts self into every key. That keeps every instance alive for as long as the cache holds its entries, and instances that compare unequal never share results. Prefer caching a module-level function that takes only the values it needs. The pitfalls chapter returns to this case.
Summary of when to use cache
| Situation | Use `cache`? |
|---|---|
| Pure function, small or bounded set of possible arguments | Yes |
| Recursive function with overlapping subproblems | Yes |
| Arguments are lists, dicts, or sets | Not directly; convert to tuples or frozensets first |
| Many distinct arguments over a long-running process | No; use `lru_cache` with `maxsize` |
| Function reads time, files, network, or changing state | No |
| Function must run its side effects every time | No |
Exercises
Exercise
A function decorated with @cache is called as area(3), then area(3, unit="cm"), then area(3, "cm"), where the signature is area(size, unit="cm"). What do cache_info().misses and currsize show after these three calls, and why?
Show answer
Both show 3. The key is built from the arguments as written, so a call with only a positional argument, a call with a keyword argument, and a call with two positional arguments produce three different keys, even though they mean the same thing to the function. Defaults are not filled in before the key is built.
Exercise
This function is decorated with @cache and returns a list: def neighbors(x): return [x - 1, x + 1]. A caller does r = neighbors(5); r.append(99). What does neighbors(5) return afterward, and what is the safest fix?
Show answer
It returns [4, 6, 99]. The cache stores a reference to the list, so the caller's change is visible to everyone. The safest fix is to return an immutable value, such as the tuple (x - 1, x + 1), or to have the caller copy the list before changing it.
Exercise
Write a cached function that returns the sum of a list of numbers, then call it with the list [1, 2, 3] without raising an error.
Show answer
from functools import cache @cache def total(items): return sum(items) numbers = [1, 2, 3] print(total(tuple(numbers))) # 6 Lists are unhashable, so convert the list to a tuple before calling the cached function.