Meaning
It decorates a function with `functools.lru_cache`, creating a cache that stores the results of recent calls keyed by the function arguments. This avoids recomputing expensive pure functions when they are called repeatedly with the same inputs, reducing CPU time. Use it when the function is deterministic and its arguments are hashable.
Primary Function
Memoization
Communicative Purpose
Speed up expensive pure functions by reusing recent results.
Pattern
@functools.lru_cache(maxsize=maxsize)
Core Structure
@functools.lru_cache(maxsize=...)
Função primária
Memoization
Propósito comunicativo
Speed up expensive pure functions by reusing recent results.
Situações de gatilho
Algorithms: computing Fibonacci numbers with overlapping subproblems; Web services: caching deterministic API responses; Data analysis: repeatedly evaluating expensive statistical functions
Contextos
Standard Python codebases, data‑science scripts, web services, any project using the functools module.
Padrão
@functools.lru_cache(maxsize=maxsize)
Estrutura central
@functools.lru_cache(maxsize=...)
Slots de substituição
maxsize: int or None, function name: identifier, parameters: comma‑separated identifiers, body: statements
Colocados típicos
- def
- expensive computation
- pure function
- recursion
- API call
Substituições comuns
- maxsize=None for unbounded cache
- use functools.cache (Python 3.9+) for default unlimited cache
- replace with cachetools.cached for TTL or LFU strategies
Erros comuns
Using mutable or unhashable arguments (e.g., lists) as cache keys; forgetting to import functools; decorating functions with side effects; setting maxsize too high causing memory pressure.
Similar / contraste
Manual dict‑based memoization (explicit cache dict) versus @functools.lru_cache; @functools.cache (unlimited) which differs by having no size limit.
Interferências
Coming from JavaScript, do not assume the cache persists across process restarts; coming from Java, do not expect thread‑safety without locks.
Família do chunk
- memoization
- caching
- decorator
Nuance
Do not use on functions that depend on external state or have observable side effects; large maxsize values can increase memory usage; cache is per‑process.
Efeito pragmático
Reduces CPU time for repeated calls, making programs feel faster and more responsive.
Dica de memória
Memoize with limited size – ‘LRU cache decorator’.
Nota
In Python 3.9+, functools.cache is equivalent to functools.lru_cache(maxsize=None).
Upgrade path
Use cachetools.cached with TTLCache for time‑based eviction or LFUCache for frequency‑based eviction.
Log in to save chunks.