functools.lru_cache(maxsize=None)
Performance Patterns

Meaning

A decorator that caches the results of a function call, storing results in an unbounded LRU cache so repeated calls with the same arguments return the cached value instead of recomputing.

Primary Function

Memoization decorator that caches function results using a least-recently-used (LRU) cache with unlimited size when maxsize=None.

Communicative Purpose

Indicates that the decorated function should be memoized for performance, signaling that its results are safe to cache and reuse.

Pattern

functools.lru_cache(maxsize=None)(func)

Core Structure

functools.lru_cache(maxsize=None)(func)

Função primária

Memoization decorator that caches function results using a least-recently-used (LRU) cache with unlimited size when maxsize=None.

Propósito comunicativo

Indicates that the decorated function should be memoized for performance, signaling that its results are safe to cache and reuse.

Situações de gatilho

When a pure function is called repeatedly with the same arguments When computing expensive results that can be cached When implementing memoization for recursive functions like Fibonacci

Contextos

Performance optimization Recursive algorithms API response caching Expensive computations with repeated inputs

Padrão

functools.lru_cache(maxsize=None)(func)

Estrutura central

functools.lru_cache(maxsize=None)(func)

Slots de substituição

{"func":"any callable function"}

Colocados típicos

  • def return @ lambda recursive

Substituições comuns

  • maxsize=128 maxsize=64 typed=True

Erros comuns

Using lru_cache on functions with mutable arguments Forgetting that the cache is per-function instance Using lru_cache on methods without considering self

Similar / contraste

functools.lru_cache(maxsize=128) – bounded cache functools.cache – Python 3.9+ unbounded cache (equivalent to maxsize=None) functools.lru_cache(typed=True) – treats arguments of different types as distinct

Interferências

Do not use on functions with side effects; results may be stale Mutable arguments (like lists, dicts) cannot be used as keys unless made hashable

Família do chunk

  • functools.lru_cache
  • functools.cache
  • functools.partial
  • functools.wraps

Nuance

When maxsize=None, the cache can grow without bound; use only when the set of possible arguments is bounded or memory is not a concern.

Efeito pragmático

Signals to readers that the function is pure and its results are safe to cache, improving perceived performance.

Dica de memória

Think of a librarian who remembers every book request forever (unlimited cache).

Nota

Equivalent to functools.cache in Python 3.9+; the decorator returns a wrapper that replaces the original function.

Upgrade path

Consider using functools.cache (Python 3.9+) for clearer syntax when unbounded caching is desired.

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

Log in to save chunks.