Advertisement
Intermediate Python, Decorators

How do you use functools.lru_cache to add memoization to a function with a single decorator?

Short answer

@functools.lru_cache(maxsize=N) automatically caches a function's return values keyed by its arguments, returning the cached result on repeated calls with the same arguments instead of recomputing — maxsize controls how many distinct argument combinations are cached before older…

Save Python mock interview
Advertisement
AModel answer
@functools.lru_cache(maxsize=N) automatically caches a function's return values keyed by its arguments, returning the cached result on repeated calls with the same arguments instead of recomputing — maxsize controls how many distinct argument combinations are cached before older ones are evicted (LRU policy).
from functools import lru_cache

@lru_cache(maxsize=128)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

fibonacci(30)  # fast, thanks to automatic caching of overlapping subcalls
Real-world example
Speeding up a recursive Fibonacci calculation or an expensive pure computation called repeatedly with the same arguments.
Likely follow-ups
  • What does passing maxsize=None to lru_cache do, and when would that be risky for memory usage?
Related topics