Meaning
@lru_cache wraps a function to cache its return values based on arguments, using a least-recently-used eviction policy when maxsize is exceeded. It avoids expensive recomputation of pure functions with repeated inputs. You reach for it when a deterministic function is called multiple times with the same arguments and you want to speed up execution.
Primary Function
Memoization
Communicative Purpose
Avoids expensive recomputation of pure functions by caching their results.
Pattern
@lru_cache(maxsize=max_size)
Core Structure
@lru_cache()
Função primária
Memoization
Propósito comunicativo
Avoids expensive recomputation of pure functions by caching their results.
Situações de gatilho
Web development: caching expensive database query results in a view function; Data processing: memoizing recursive Fibonacci calculation; Scientific computing: caching intermediate results in iterative algorithms
Contextos
Python standard library, web frameworks like Flask and Django, data science pipelines
Padrão
@lru_cache(maxsize=max_size)
Estrutura central
@lru_cache()
Slots de substituição
max_size: int ≥ 0, maximum number of cached entries
Colocados típicos
- functools.wraps
- recursive functions
- pure functions
Substituições comuns
- Using a custom dictionary cache (more control but manual management)
- using @cache (Python 3.9+ simpler LRU cache without maxsize)
- using lru_cache without maxsize (unbounded cache)
Erros comuns
Applying @lru_cache to a function with mutable arguments (cause: unhashable types; consequence: TypeError); forgetting to import lru_cache from functools (cause: missing import; consequence: NameError); setting maxsize=0 (cause: misunderstanding; consequence: no caching)
Similar / contraste
@cache (unbounded LRU cache introduced in Python 3.9); @staticmethod (decorator for utility functions); manual memoization with dict (more verbose)
Interferências
Coming from Java: may attempt to use static fields for caching → Python's lru_cache is function-specific and thread-safe in CPython due to GIL but not guaranteed across interpreters; Coming from C++: may try to use std::unordered_map directly → lru_cache provides automatic eviction policy
Família do chunk
- @cache
- @staticmethod
- @property
- manual dict memoization
Nuance
Do not use on functions with side effects or non-deterministic output; caching consumes memory proportional to maxsize and can cause memory pressure; the cache key is based on argument values; unhashable arguments raise TypeError
Efeito pragmático
Reduces latency and CPU usage for repeated pure function calls, enabling faster response times in web services and scientific computations.
Dica de memória
Like a librarian who keeps the most recently requested books on the front desk for quick access.
Nota
In Python 3.8+, lru_cache returns a wrapper with a cache_info() function for statistics.
Upgrade path
Consider using @functools.cache for unbounded caching or implementing a TTL-based cache for time-sensitive data.
Log in to save chunks.