Sub topic 11
When caching goes wrong
This chapter assumes you know how functools.cache and lru_cache work, what hashable means, and how cache_info() reports hits and misses. Caching is safe only when its assumptions hold. Four common failures are unhashable arguments, impure functions, unbounded memory growth, and instance methods.
Unhashable arguments
A cache stores results in a dictionary keyed by the call's arguments. Dictionary keys must be hashable, so every argument must be hashable too. Lists, dicts, and sets are not.
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 pass a tuple, or a frozenset when order does not matter. Convert at the call site, or write a thin uncached wrapper that converts and then calls the cached function.
Impure functions
A cache assumes the same arguments always give the same result. If a function reads a clock, a file, a database, or a random number, the cache freezes the first answer.
import time
from functools import cache
@cache
def timestamp(label):
return f"{label}: {time.time()}"
first = timestamp("start")
time.sleep(0.01)
second = timestamp("start")
print(first == second) # True, the second call returned the stale valueSide effects are also skipped on a hit. If the function prints, writes a file, or updates a counter, none of that happens when the result comes from the cache. Cache only pure functions, or call cache_clear() whenever the underlying data changes.
A related trap is mutable return values. The cache returns the same object every time, so a caller who modifies a returned list changes what later callers receive.
from functools import cache
@cache
def defaults():
return ["a", "b"]
x = defaults()
x.append("c")
print(defaults()) # ['a', 'b', 'c']Return a tuple, or copy the list before handing it out.
Unbounded memory growth
cache never evicts anything. A long-running service that calls a cached function with many different arguments, such as user IDs or request paths, keeps every result alive for the life of the process.
from functools import lru_cache
@lru_cache(maxsize=1024)
def load_profile(user_id):
return {"id": user_id}With maxsize set, the least recently used entries are discarded once the cache is full. Pick a size from cache_info(): if currsize sits at maxsize and misses stay high, the cache is too small. If it never fills, the bound costs you nothing.
Instance methods
Decorating a method puts self in the cache key, which causes two problems. The cache holds a strong reference to every instance it has seen, so those objects are never garbage collected while their entries remain. The instance must also be hashable, and two instances that compare equal but hash differently get separate entries.
from functools import lru_cache
class Report:
def __init__(self, name):
self.name = name
@lru_cache(maxsize=None)
def render(self):
return f"Report {self.name}"
a = Report("q1")
print(a.render())
print(Report.render.cache_info().currsize) # 1
del a # the cache still references the instance, so it stays aliveThere is one cache for the whole class, not one per instance. Alternatives are to cache a module-level function that takes only the values it needs, or to use functools.cached_property for a value computed once per instance.
from functools import cached_property
class Report:
def __init__(self, name):
self.name = name
@cached_property
def title(self):
return f"Report {self.name}"
print(Report("q1").title) # Report q1Choosing a response
Summary of failures
| Problem | Symptom | Fix |
|---|---|---|
| Unhashable argument | `TypeError: unhashable type` | Pass a tuple or frozenset |
| Impure function | Stale or repeated values | Do not cache, or call `cache_clear()` |
| Mutable result | Callers change shared data | Return an immutable value or a copy |
| Unbounded growth | Memory rises over time | Use `lru_cache(maxsize=N)` |
| Instance method | Instances never freed | Use `cached_property` or a module-level function |
Exercise
A web service decorates def get_page(url) with @cache, and the function downloads the page. After a week, the process uses far more memory and some pages are out of date. Which two problems from this chapter are present, and what change addresses both?
Show answer
The function is impure (the page changes over time, so the cache returns stale content) and the cache is unbounded (every URL ever requested stays in memory). Switching to @lru_cache(maxsize=N) limits memory, and calling cache_clear() on a schedule, or not caching the download itself, handles staleness. Caching a pure step that parses already-downloaded content would be safe.
Exercise
Why does @lru_cache on a method keep objects alive, and what does cached_property do differently?
Show answer
The cache is shared by the class and includes self in each key, so it holds a strong reference to every instance it has seen. cached_property stores the value in each instance's own __dict__, so it is freed together with the instance.