Meaning
The @lru_cache decorator wraps a function to store its results in a least-recently-used cache, so repeated calls with the same arguments return instantly without re-executing the function body. This avoids redundant computation in recursive or expensive pure functions, dramatically improving performance when the same inputs occur frequently. It is applied when a function is deterministic and its output depends only on its inputs, and when the cost of recomputation outweighs the memory overhead of caching.
Primary Function
Memoization
Communicative Purpose
Avoids redundant computation by caching function results based on input arguments
Pattern
@lru_cache(maxsize=limit) def func_name(num): return num if num<2 else func_name(num-1)+func_name(num-2)
Core Structure
@lru_cache(maxsize=...) def ...(...): return ... if ... < ... else ...(...-...)+...(...-...)
Função primária
Memoization
Propósito comunicativo
Avoids redundant computation by caching function results based on input arguments
Situações de gatilho
Algorithm optimization: computing Fibonacci numbers recursively with overlapping subproblems Dynamic programming: avoiding repeated subproblem calculations in recursive algorithms Performance tuning: caching expensive pure functions such as JSON parsing or complex transformations
Contextos
Python standard library functools, recursive algorithms, dynamic programming, functional programming techniques
Padrão
@lru_cache(maxsize=limit) def func_name(num): return num if num<2 else func_name(num-1)+func_name(num-2)
Estrutura central
@lru_cache(maxsize=...) def ...(...): return ... if ... < ... else ...(...-...)+...(...-...)
Slots de substituição
maxsize: int > 0, function_name: identifier, parameter: identifier
Colocados típicos
- functools.wraps
- recursive algorithms
- dynamic programming techniques
Substituições comuns
- Manual memoization using a dictionary: more control but boilerplate
- @cache (Python 3.9+): simpler but less configurable
Erros comuns
Forgetting to import lru_cache from functools: causes NameError when the decorator is used Using mutable arguments as cache keys: leads to incorrect caching because mutable objects are not hashable Applying lru_cache to functions with side effects: results in unexpected behavior because cached returns suppress side effects on subsequent calls
Similar / contraste
@cache: built-in decorator with unlimited size (Python 3.9+) @lru_cache(maxsize=None): unbounded cache that grows indefinitely Manual dict memoization: explicit control over cache key generation and eviction policy
Interferências
Coming from Java: may use synchronized memoization; Python's lru_cache is thread-safe for CPython GIL but not guaranteed for custom implementations Coming from C++: may try to use static variables inside functions; lru_cache provides automatic per-function cache without manual static management Coming from Haskell: may expect lazy evaluation to avoid recomputation; lru_cache works with eager evaluation and requires explicit caching
Família do chunk
- @cache
- @lru_cache
- functools.partial
- manual memoization
Nuance
Do not use when function results depend on external state or time, as caching will return stale values Memory usage grows with number of unique argument combinations; consider setting a finite maxsize to prevent unbounded growth The cache operates per-function instance; decorating a method in a class shares the cache across all instances unless the method is overridden per instance
Efeito pragmático
Reduces time complexity from exponential to linear for overlapping subproblems; improves latency and throughput in recursive algorithms and expensive pure functions
Dica de memória
Like a librarian who remembers which books you've asked for, so you don't have to fetch them again from the shelves.
Nota
The decorator is not thread-safe by default; concurrent modifications require external synchronization
Upgrade path
@cache (unbounded LRU cache)
Log in to save chunks.