PyDocs

Nav

Functional Programming Modules

lru_cache

functools

decorator · Added in 3.2 (source)
  • @lru_cache(user_function)
  • @lru_cache(maxsize=128, typed=False)
Least-recently-used cache decorator.

If *maxsize* is set to None, the LRU features are disabled and the cache
can grow without bound.

If *typed* is True, arguments of different types will be cached
separately.  For example, f(decimal.Decimal("3.0")) and f(3.0) will be
treated as distinct calls with distinct results.  Some types such as
str and int may be cached separately even when typed is false.

Arguments to the cached function must be hashable.

View the cache statistics named tuple (hits, misses, maxsize, currsize)
with f.cache_info().  Clear the cache and statistics with
f.cache_clear().  Access the underlying function with f.__wrapped__.

See:  https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU)
Changed in 3.3, 3.8, 3.9
  • 3.3: Added the typed option.
  • 3.8: Added the user_function option.
  • 3.9: Added the function cache_parameters()
Members of lru_cache

c

cache_clear
The decorator also provides a cache_clear() function for clearing or invalidating the cache.
cache_info
To help measure the effectiveness of the cache and tune the maxsize parameter, the wrapped function is instrumented with a cache_info() function that returns a named tuple showing hits, misses, maxsi…
1 Example
@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = f'https://peps.python.org/pep-{num:04d}'
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
from the Python docs
See Also
No see-alsos for functools/lru_cache
0 Notes
No notes for lru_cache