
Why cache at all?
Every time you call an expensive function with the same inputs, you pay the full cost again. functools.lru_cache memoizes results keyed on the arguments, so repeated calls with identical inputs return instantly — no recomputation.
The 30-second version
from functools import lru_cache
@lru_cache(maxsize=128)
def fib(n: int) -> int:
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(50)) # blazing fast
print(fib.cache_info())
Without the cache, fib(50) explodes into roughly 40 billion recursive calls. With it, each unique n is computed once and reused — about 51 real evaluations total.
Trap 1 — unhashable arguments silently break it
lru_cache stores results in a dict, so every argument must be hashable. Pass a list and you get a TypeError:
@lru_cache
def normalize(items):
return sorted(items)
normalize([3, 1, 2]) # TypeError: unhashable type: 'list'
Fix by converting to a tuple at the boundary:
@lru_cache
def normalize(items: tuple):
return sorted(items)
normalize(tuple([3, 1, 2]))
Trap 2 — caching instance methods caches on self
When you decorate a method, self becomes part of the cache key. If the class isn’t hashable, you get a TypeError. Even when it is hashable, the cache is attached to the function object and is shared across all instances — usually not what you want.
class PriceBook:
def __init__(self, rates):
self.rates = rates
@lru_cache # caches on (self, product_id); self must be hashable
def price(self, product_id):
return self.rates[product_id] * 1.2
Prefer caching a free function, or make the class deliberately hashable:
class PriceBook:
def __init__(self, rates):
self.rates = rates
def __hash__(self):
return id(self)
@lru_cache
def _price(self, product_id):
return self.rates[product_id] * 1.2
def price(self, product_id):
return self._price(product_id)
Trap 3 — the cache grows and never forgets (unless you cap it)
maxsize=128 keeps the 128 most-recently-used entries and evicts the rest (LRU = least recently used). Set maxsize=None for an unbounded cache — convenient, but it leaks memory for inputs that never repeat. Always expose .cache_clear() in tests or teardown:
fib.cache_clear() # wipe everything
print(fib.cache_info()) # CacheInfo(hits=0, misses=0, maxsize=128, currsize=0)
Takeaways
- Use
lru_cachefor pure functions with repeatable, hashable inputs. - Watch for unhashable args and instance-method
selfhashing. - Cap
maxsizeand call.cache_clear()in tests/cleanup. - Inspect
.cache_info()to confirm the hits are actually happening before assuming a speedup.