Sub topic 11
When caching goes wrong
This chapter assumes you can write decorators with @, know that cache and lru_cache memoize results by argument, and know which built-in types are hashable (tuple, str, int) and which are not (list, dict, set). Caching is easy to add and hard to notice when it is wrong. A cached function that misbehaves usually returns plausible results, not errors. This chapter covers six failure modes and the fix for each.
How the cache decides
A cached function stores results in a dictionary. The key is built from the call's arguments and the value is the return value. Three consequences follow from that:
- Every argument must be hashable, or the key cannot be built.
- Calls with equal arguments return the stored result, even when the real answer would have changed.
- Entries stay in the dictionary, and keep their keys alive, until they are evicted or cleared.
Each pitfall below comes from one of these.
Unhashable arguments
Passing a list, dict, or set to a cached function raises TypeError, because the key cannot be hashed.
from functools import cache
@cache
def total(items):
return sum(items)
try:
total([1, 2, 3])
except TypeError as exc:
print(exc) # unhashable type: 'list'
print(total((1, 2, 3))) # 6There are two fixes. The first is to have callers pass tuples. The second is to keep a friendly public function and cache a private one behind it:
from functools import cache
@cache
def _total(items):
return sum(items)
def total(items):
return _total(tuple(items))
print(total([1, 2, 3])) # 6
print(total([1, 2, 3])) # 6, served from the cacheDo not "fix" this by converting the argument to a string with str(items) or repr(items). Two different objects can print the same text, and two equal objects can print differently. Use a real hashable equivalent such as a tuple or a frozenset.
Impure functions
Memoization is only correct for pure functions, meaning functions whose result depends solely on their arguments and that have no side effects. A cached function that reads the clock, a file, a database, or an environment variable will keep returning the first answer it saw.
import time
from functools import cache
@cache
def stamp(label):
return f"{label}: {time.time()}"
first = stamp("start")
time.sleep(0.05)
second = stamp("start")
print(first == second) # True, the clock reading is frozenSide effects are skipped on a cache hit. If a function writes a log line, sends an email, or increments a counter, none of that happens when the result comes from the cache.
If you still want caching, because the data changes only occasionally, make the changing input an explicit argument. A common pattern is a time bucket that changes every N seconds, which gives a crude time-to-live:
import time
from functools import lru_cache
def _bucket(seconds):
return int(time.monotonic() // seconds)
@lru_cache(maxsize=128)
def _lookup(key, bucket):
print(f"looking up {key}")
return key.upper()
def lookup(key):
return _lookup(key, _bucket(60))
lookup("alpha")
lookup("alpha") # same bucket, no second "looking up"The bucket argument is never used inside _lookup. It exists only so that the cache key changes once a minute. The old entries are not removed when the bucket changes. They stay until maxsize pushes them out, which is why this version uses lru_cache and not cache.
Unbounded growth
cache has no size limit. Each distinct set of arguments adds an entry that is never removed. For inputs from a small, fixed domain this is fine. For inputs from users, requests, or timestamps, it is a slow memory leak that appears only in production.
from functools import lru_cache
@lru_cache(maxsize=100)
def parse(n):
return str(n)
for i in range(10_000):
parse(i)
print(parse.cache_info())
# CacheInfo(hits=0, misses=10000, maxsize=100, currsize=100)currsize stays at 100. Older entries are evicted, least recently used first. Choose between the two decorators this way:
| Situation | Choice |
|---|---|
| Small, known set of inputs (recursive math, a handful of config keys) | `cache` |
| Inputs come from outside, or the set is open-ended | `lru_cache(maxsize=N)` |
| Results are large objects | `lru_cache` with a small `N` |
A bound only helps if the entries are not all useful. If every call uses a new key, the hit rate is near zero and the cache adds overhead and holds memory for nothing. Check cache_info() and remove the decorator if hits stays low.
Instance methods
Decorating a method with cache or lru_cache looks natural and causes two problems.
First, self is part of the key. That means the instance must be hashable. A class that defines __eq__ without __hash__ becomes unhashable, and every cached method call raises TypeError.
Second, the cache is stored on the function, which is shared by the whole class. The key holds a strong reference to each self it has seen, so those instances can never be garbage collected while their entries remain:
import gc
import weakref
from functools import lru_cache
class Report:
def __init__(self, name):
self.name = name
self.payload = bytearray(1_000_000)
@lru_cache(maxsize=None)
def title(self):
return self.name.title()
report = Report("q3 sales")
report.title()
ref = weakref.ref(report)
del report
gc.collect()
print(ref() is None) # False, the cache still holds the instanceThere are two better options. For a method with no arguments besides self, use functools.cached_property. It stores the value in the instance's own __dict__, so it disappears with the instance:
import gc
import weakref
from functools import cached_property
class Report:
def __init__(self, name):
self.name = name
@cached_property
def title(self):
return self.name.title()
report = Report("q3 sales")
print(report.title) # Q3 Sales
ref = weakref.ref(report)
del report
gc.collect()
print(ref() is None) # TrueFor a method with arguments, create the cache per instance in __init__, so each cache lives and dies with its object:
import gc
import weakref
from functools import lru_cache
class Report:
def __init__(self, name):
self.name = name
self.section = lru_cache(maxsize=32)(self._section)
def _section(self, number):
return f"{self.name} / section {number}"
report = Report("q3")
print(report.section(2)) # q3 / section 2
ref = weakref.ref(report)
del report
gc.collect()
print(ref() is None) # TrueThis creates a reference cycle (the instance holds the cache, and the cache holds the bound method, which holds the instance). The cyclic garbage collector can free it, but it is not freed the instant the last outside reference goes away.
Shared mutable results
A cache hit returns the stored object itself, not a copy. If the function returns a mutable object and a caller changes it, every later caller sees the change:
from functools import cache
@cache
def defaults():
return {"retries": 3}
config = defaults()
config["retries"] = 99
print(defaults()) # {'retries': 99}Return immutable values (tuples, frozensets, strings, numbers) from cached functions. If you cannot, return a copy from a thin wrapper, or document that callers must not modify the result.
Keys that look equal
The key is built from the argument values, so a few different-looking calls behave in surprising ways.
- Positional and keyword calls are different keys.
f(1)andf(x=1)each compute and store a result, so you can pay for the same work twice. - Arguments that compare equal and hash equal share an entry.
1,1.0, andTrueare all the same key.
from functools import lru_cache
@lru_cache(maxsize=None)
def identity(x):
return x
print(identity(1)) # 1
print(identity(1.0)) # 1, the cached int comes back, not 1.0
@lru_cache(maxsize=None, typed=True)
def identity_typed(x):
return x
print(identity_typed(1)) # 1
print(identity_typed(1.0)) # 1.0Setting typed=True stores separate entries for different argument types. This matters when the result depends on the type, for example when a function returns x itself or formats it.
Two more behaviors are worth knowing:
- Exceptions are not cached. If the function raises, nothing is stored, and the next call runs the function again.
- The cache is thread-safe in the sense that its internal data stays consistent. It does not stop two threads that call with the same new arguments at the same moment from both running the function. For expensive or side-effecting work, add your own lock.
Deciding whether to cache
The diagram turns the pitfalls into a checklist you can run before adding a decorator.
Summary of failure modes
| Pitfall | Symptom | Fix |
|---|---|---|
| Unhashable argument | `TypeError: unhashable type` | Pass or convert to a tuple or frozenset |
| Impure function | Stale or frozen results, skipped side effects | Make the changing input an argument, or do not cache |
| Unbounded growth | Memory rises over time | `lru_cache(maxsize=N)` |
| Cached instance method | Instances never freed, or `TypeError` from `__eq__` | `cached_property` or a per-instance cache |
| Mutable result | Callers corrupt each other's data | Return immutable values or copies |
| Equal-looking keys | Duplicate work, or a wrong type returned | Be consistent in how you call it, or use `typed=True` |
Exercise
A class has a method price(self, sku) decorated with @lru_cache(maxsize=None). The service that uses it creates one Catalog object per incoming request. After a few days, memory use has grown steadily. Explain why, and give one fix.
Show answer
The cache belongs to the function, not to each instance, and its keys include self. Every Catalog object ever used to call price is stored as part of a key, so the cache holds a strong reference to it. With maxsize=None nothing is evicted, so no request-scoped Catalog is ever garbage collected. One fix is to create a per-instance cache in __init__, with self.price = lru_cache(maxsize=256)(self._price), so the cache is freed with the object. Another is to move the pricing into a module-level function that takes only hashable data such as sku, cache that function with a bounded maxsize, and call it from the method.
Exercise
What does this code print, and why is it a problem? from functools import cache @cache def gettags(): return ["new"] gettags().append("sale") print(get_tags())
Show answer
It prints ['new', 'sale']. The cache returns the same list object on every call, so the append changed the stored result. Every later caller sees the modified list. To avoid this, return an immutable value such as the tuple ("new",), or return list(...) from a wrapper function so each caller gets its own copy.