Sub topic 3
Bounding Memory with `lru_cache`
Assume you know function decorators, keyword arguments, and the difference between hashable tuples and unhashable lists. functools.lru_cache memoizes results while limiting how many entries remain in memory.
Bounding memory with `lru_cache`
lru_cache means “least recently used cache.” With maxsize=2, the cache keeps two results. When a third distinct argument arrives, it removes the result used least recently.
from functools import lru_cache
@lru_cache(maxsize=2)
def square(n):
print(f"computing {n}")
return n * n
square(1)
square(2)
square(1) # Cache hit
square(3) # Removes 2
square(2) # Computes again| Decorator | Memory behavior | Best use |
|---|---|---|
| `@cache` | Unbounded growth | A small, stable set of inputs |
| `@lru_cache(maxsize=N)` | Keeps at most `N` entries | A potentially large input set |
Choose lru_cache when old results should be discarded. A small maxsize saves memory but can cause more recomputation.
Measuring and clearing a cache
A cached function provides cache_info() and cache_clear():
print(square.cache_info())
# CacheInfo(hits=1, misses=4, maxsize=2, currsize=2)
square.cache_clear()
print(square.cache_info())
# CacheInfo(hits=0, misses=0, maxsize=2, currsize=0)A hit reuses a stored result. A miss runs the function. Use these counters to check whether caching helps rather than assuming it does.
When caching goes wrong
Caching is unsafe or ineffective in several cases:
- An impure function depends on time, files, network data, or mutable global state. A cached result can become stale.
- An unbounded cache receives many unique inputs and grows until it consumes too much memory.
- A function accepts lists or dictionaries, which are unhashable.
- An instance method caches
selfas part of its key. Entries can keep instances alive and may mix poorly with changing object state.
Putting the tools together
Decorators can be stacked. wraps preserves metadata, while cache stores results.
import functools
from functools import cache
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}{args}")
return func(*args, **kwargs)
return wrapper
@log_calls
@cache
def double(n):
return n * 2
double(4)
double(4) # Logged again; the result comes from the cache
print(double.__name__) # doubleExercise
Why might lru_cache(maxsize=2) compute a value again after it was previously cached?
Show answer
A later call can evict that value when the cache reaches its two-entry limit.