Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Memory & performanceMiddleCommonPerformance

How does `functools.lru_cache` speed up a function, and what constraints does it place on that function's arguments?

Answer

`@functools.lru_cache(maxsize=128)` wraps a function so that each unique combination of arguments is computed once and its result is stored in an internal dictionary keyed by those arguments; subsequent calls with the same arguments return the cached result instantly instead of recomputing it, evicting the least-recently-used entry once `maxsize` is exceeded. Because the cache is keyed by the arguments themselves, every argument must be hashable — passing a `list` or `dict` argument raises a `TypeError` — and the function should be pure (its result should depend only on its arguments, with no side effects or external state), or cached results will silently become stale or incorrect.

Strong answer includes

  • caches results keyed by argument combination, evicts least-recently-used past maxsize
  • arguments must be hashable, lists/dicts raise TypeError
  • function should be pure or cached results go stale

Practical example

Python example
@lru_cache(maxsize=None)
def fib(n): return n if n < 2 else fib(n-1) + fib(n-2)

turns an exponential-time naive recursive Fibonacci into a linear-time one by never recomputing the same `n` twice.

#performance#functools#caching

Sources

functools — Higher-order functions and operations on callable objectsPython Software Foundation · lru_cache, partial, wraps, reduce and singledispatch behavior