@cache(maxsize=128) def fib(n): return n if n<2 else fib(n-1)fib(n-2)
Decorators & Metaclasses

Meaning

The @lru_cache decorator from functools memoizes a pure function's return values in a bounded LRU cache, eliminating redundant recomputation for repeated calls with identical arguments. It addresses the exponential time blowup of naive recursive algorithms by trading memory for speed. You reach for it whenever a deterministic function is invoked repeatedly with overlapping inputs, most commonly in recursive divide-and-conquer or dynamic-programming solutions.

Primary Function

Memoization

Communicative Purpose

Prevents redundant recomputation by caching return values of pure function calls with identical arguments.

Pattern

@lru_cache(maxsize=maxsize) def func(arg): return ...

Core Structure

@lru_cache(...) def ...( ... ): ...

Função primária

Memoization

Propósito comunicativo

Prevents redundant recomputation by caching return values of pure function calls with identical arguments.

Situações de gatilho

Recursive algorithms: overlapping subproblems cause exponential recomputation (e.g., Fibonacci, binomial coefficients); Expensive pure functions: repeated lookups or transformations with identical inputs across a program run; Dynamic programming: top-down memoization needed without restructuring into bottom-up loops

Contextos

Python standard library, algorithmic code, data processing pipelines, API response caching, combinatorial computations

Padrão

@lru_cache(maxsize=maxsize) def func(arg): return ...

Estrutura central

@lru_cache(...) def ...( ... ): ...

Slots de substituição

maxsize: int >= 0 or None (cache capacity, default 128), func: callable name, arg: one or more hashable parameters, ...: function body returning cached value

Colocados típicos

  • functools module
  • recursive functions
  • pure functions
  • hashable arguments
  • cache_info()
  • cache_clear()

Substituições comuns

  • @cache (Python 3.9+): unbounded cache with no eviction overhead but unlimited memory growth
  • Manual dict memoization: full control over cache lifecycle but more boilerplate and no built-in thread safety
  • @lru_cache(maxsize=None): equivalent to @cache
  • retains all entries indefinitely

Erros comuns

Applying @lru_cache to a function with unhashable arguments (e.g., list, dict) → TypeError at call time; Forgetting that cache persists across calls in long-running processes → stale data or unbounded memory growth; Caching a method on a class without considering self in the cache key → cache retains reference to self, potential memory leak; Using @lru_cache on a function with side effects or non-deterministic output → cached results become stale or incorrect

Similar / contraste

@cache: unbounded version with no maxsize parameter and no eviction; @cached_property: caches per-instance attribute on first access, not per-call; Manual memoization dict: explicit control over cache lifecycle and eviction policy

Interferências

Coming from JavaScript: may expect cache to handle non-hashable types like plain objects → Python requires all positional and keyword arguments to be hashable; Coming from Java: may assume @lru_cache works like @Cacheable with TTL expiration → Python's lru_cache has no built-in time-based expiration

Família do chunk

  • @lru_cache
  • @cache
  • @cached_property
  • functools module
  • memoization
  • dynamic programming

Nuance

Do NOT use @lru_cache on functions with side effects, I/O operations, or non-deterministic output (e.g., random, datetime.now) — cached results will be wrong on subsequent calls; Each unique argument tuple consumes one cache entry; maxsize=None on a function called with many distinct arguments can exhaust memory; cache_info() and cache_clear() are attached to the decorated function for runtime introspection and manual eviction

Efeito pragmático

Turns O(2^n) recursive algorithms into O(n) with O(n) memory, making previously impractical recursive solutions viable in production without rewriting as iterative loops.

Dica de memória

Like a smart assistant who writes down answers to questions they have already solved — no need to re-solve if the same question comes again.

Nota

In Python 3.9+, @cache is shorthand for @lru_cache(maxsize=None). The maxsize parameter defaults to 128; set to None for unbounded cache. The typed=True parameter (added in 3.8) treats arguments of different types as distinct cache keys.

Upgrade path

Custom cache eviction strategies (TTLCache from cachetools), @lru_cache with typed=True for type-aware caching, per-instance caching with @cached_property

Frequência: HighFormulaicidade: Semi-fixedTipo de construção: decoratorPrioridade de aquisição: Active recallPrioridade de output: BothTag de espaçamento: Short-termIdioma?: Sim

Log in to save chunks.