@functools.lru_cache(maxsize=128)
Decorators & Metaclasses

Meaning

A decorator that caches the results of a function call based on its arguments, using a least-recently-used eviction policy when the cache exceeds maxsize entries.

Primary Function

Memoize function results to avoid expensive recomputation.

Communicative Purpose

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

Pattern

@functools.lru_cache(maxsize=<N>)

Core Structure

@functools.lru_cache

Função primária

Memoize function results to avoid expensive recomputation.

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 When the function computation is expensive relative to cache lookup When the function's output depends only on its inputs (pure function)

Contextos

Performance optimization in recursive algorithms (e.g., Fibonacci, factorial) Caching expensive I/O or computation results in web services Memoizing pure functions in functional-style Python code

Padrão

@functools.lru_cache(maxsize=<N>)

Estrutura central

@functools.lru_cache

Slots de substituição

{"maxsize":"integer >= 1, or None for unlimited cache"}

Colocados típicos

  • def def return @ functools

Substituições comuns

  • @lru_cache @functools.lru_cache() @functools.lru_cache(maxsize=None)

Erros comuns

Using lru_cache on functions with mutable arguments (e.g., lists, dicts) leading to incorrect caching Forgetting to import functools Setting maxsize too low causing excessive evictions, or too high causing excessive memory use

Similar / contraste

@functools.lru_cache vs @functools.cache (Python 3.9+): cache is unbounded lru_cache wrapper @functools.lru_cache vs @functools.lru_cache(maxsize=None): unbounded LRU cache

Interferências

Applying lru_cache to recursive functions without proper base case can cause infinite recursion due to caching intermediate results Using lru_cache on methods without considering self argument can cause memory leaks if not careful

Família do chunk

  • functools decorators
  • memoization techniques
  • functional programming patterns

Nuance

The cache is per-function instance; each decorated function gets its own cache. The maxsize argument controls the maximum number of entries before LRU eviction begins.

Efeito pragmático

Signals to readers that the function is pure and performance-sensitive, encouraging reuse of results.

Dica de memória

@functools.lru_cache(maxsize=128)

Nota

Python 3.9+ includes functools.cache as an alias for lru_cache(maxsize=None).

Upgrade path

Consider using @functools.cache (unbounded) or @functools.lru_cache(maxsize=None) for unbounded caching, or @functools.lru_cache(maxsize=2**30) for very large caches.

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

Log in to save chunks.