Bound Cache Size and Lifetime
Core idea
Caching exchanges memory and possible staleness for less repeated work. functools.lru_cache stores results for hashable argument combinations up to maxsize; eviction removes least recently used entries. cache_info exposes hits, misses and current size, while cache_clear resets entries and counters. Choose invalidation based on the data lifetime; maxsize alone is not a time-to-live policy.
from functools import lru_cache@lru_cache(maxsize=2)def fee(n): return n*3for n in (1, 2, 1, 3, 2): fee(n)i = fee.cache_info()print(i.hits, i.misses, i.currsize)Accessing 1 refreshes its recency. Adding 3 evicts 2, so the final call misses.
Expected output:
1 4 2Invalidate changed data
from functools import lru_cacherates = {'A': 4}@lru_cache(maxsize=8)def rate(code): return rates[code]print(rate('A'))rates['A'] = 6print(rate('A'))rate.cache_clear()print(rate('A'))The cache does not detect external state changes; explicit invalidation is necessary.
Expected output:
446Common mistake
Avoid caching side effects or mutable objects that callers may modify. Cached arguments and results are retained until eviction or clear. Thread-safe cache bookkeeping does not guarantee a single computation for simultaneous misses.
Practice
Compare maxsize=2 and maxsize=8 for the same fixed request sequence. Report hit ratio and current size, and define when a changed rate invalidates the cache.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Caching trade-offs
Check your understanding of caching trade-offs.
What is printed?
from functools import lru_cache@lru_cache(maxsize=2)def f(x): return xf(1);f(1)print(f.cache_info().hits)What is printed?
from functools import lru_cache@lru_cache(maxsize=1)def f(x): return xf(1);f.cache_clear()print(f.cache_info().currsize)Does maxsize set expiration time?
What risk arises when caching a mutable external lookup?