@functools.lru_cache
Performance Patterns

Meaning

A decorator that caches the results of a function call, storing results in an unlimited cache keyed by the function's arguments.

Primary Function

Memoization of function results to avoid redundant computation.

Communicative Purpose

Indicates that the decorated function's results should be cached for performance optimization.

Pattern

@functools.lru_cache(maxsize=None)

Core Structure

@functools.lru_cache

Função primária

Memoization of function results to avoid redundant computation.

Propósito comunicativo

Indicates that the decorated function's results should be cached for performance optimization.

Situações de gatilho

When a pure function is called repeatedly with the same arguments and the computation is expensive (e.g., recursive algorithms, expensive calculations, I/O‑bound functions).

Contextos

Performance‑critical code, recursive functions (e.g., Fibonacci), expensive pure functions, API call caching, dynamic programming.

Padrão

@functools.lru_cache(maxsize=None)

Estrutura central

@functools.lru_cache

Slots de substituição

maxsize=<int or None>

Colocados típicos

  • fibonacci
  • fib
  • expensive_func
  • recursive_func
  • api_call
  • dp_func

Substituições comuns

  • maxsize=128
  • maxsize=256
  • maxsize=64
  • @functools.lru_cache() (default maxsize=128)
  • @functools.cache (unbounded
  • Python 3.9+)

Erros comuns

Using unhashable arguments (e.g., lists, dicts) as function parameters; forgetting that the cache grows without bound when maxsize=None; assuming the cache is automatically cleared; confusing @lru_cache with @cache.

Similar / contraste

@functools.lru_cache(maxsize=128) (bounded cache), @functools.lru_cache() (default maxsize=128), @functools.cache (unbounded cache, Python 3.9+), @functools.lru_cache(maxsize=None, typed=True) (separate cache per argument type).

Interferências

Confusing @lru_cache with @cache; assuming arguments are hashable when they are not; expecting automatic cache invalidation; memory growth with an unbounded cache.

Família do chunk

  • functools decorators
  • memoization patterns

Nuance

Setting maxsize=None provides an unlimited cache, which can lead to unbounded memory consumption if the function is called with many distinct argument combinations.

Efeito pragmático

Signals that the function is pure (deterministic) and expensive, indicating an intentional optimization that trades memory for speed.

Dica de memória

@lru_cache

Nota

Use functools.cache (Python 3.9+) for unbounded caching; beware of unbounded memory growth with maxsize=None.

Upgrade path

@functools.cache (unbounded cache introduced in Python 3.9) or using functools.lru_cache with a finite maxsize for bounded caching

Tipo de construção: decoratorTag de espaçamento: Medium-term

Log in to save chunks.