On this page
functools.lru_cache
Prev: functools.cmp_to_key | Up: functools | Next: functools.partial
Rel: functools.cache, functools.cached_property, functools.cmp_to_key, functools.partial
Ref: docs.python.org — functools.lru_cache
Tags: #public #python3 #stdlib #functools
Import
import functools
from functools import lru_cache
Signature & Overview
functools.lru_cache(maxsize=128, typed=False)
Least-recently-used cache decorator.
Usage
from functools import lru_cache
@lru_cache(maxsize=128)
def square(n: int) -> int:
return n * n
assert square(5) == 25 and square(5) == 25
assert square.cache_info().hits == 1
square.cache_clear()
Gotchas
- Returns the same object reference on hits: If the cached function returns a mutable
list/dict, callers mutating it will corrupt the cached entry for everyone else. typed=Falseby default:square(3)andsquare(3.0)share a cache slot unless you passtyped=True.- Requires hashable arguments: Lists and dicts raise
TypeError.
REPL Inspect
from functools import lru_cache
help(lru_cache)
Linked from
- tuts/python3/stdlib_module/functools
- tuts/python3/stdlib_module/functools/cache
- tuts/python3/stdlib_module/functools/cached_property
- tuts/python3/stdlib_module/functools/cmp_to_key
- tuts/python3/stdlib_module/functools/partial
- tuts/python3/stdlib_module/functools/partialmethod
- tuts/python3/stdlib_module/functools/reduce
- tuts/python3/stdlib_module/functools/singledispatch
- tuts/python3/stdlib_module/functools/singledispatchmethod
- tuts/python3/stdlib_module/functools/total_ordering
- tuts/python3/stdlib_module/functools/update_wrapper
- tuts/python3/stdlib_module/functools/wraps
Related notes
- tuts/python3/stdlib_module/functools/cache Linked here; links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/cached_property Linked here; links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/cmp_to_key Linked here; links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/partial Linked here; links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/functools/partialmethod links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/reduce links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/singledispatch links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/singledispatchmethod links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/total_ordering links to this page; shared tags: #functools, #stdlib