On this page
functools.cache
Up: functools | Next: functools.cached_property
Rel: functools.cached_property, functools.cmp_to_key, functools.lru_cache, functools.partial
Ref: docs.python.org — functools.cache
Tags: #public #python3 #stdlib #functools
Import
import functools
from functools import cache
Signature & Overview
functools.cache(user_function, /)
Simple lightweight unbounded cache. Sometimes called "memoize".
Usage
from functools import cache
@cache
def fib(n: int) -> int:
return n if n < 2 else fib(n - 1) + fib(n - 2)
assert fib(30) == 832040
assert fib.cache_info().hits > 0
Gotchas
- Unbounded memory:
cacheis shorthand forlru_cache(maxsize=None). On long-running services with open-ended inputs, uselru_cache(maxsize=...)so memory doesn't grow forever. - Arguments must be hashable: Passing a
listordictraisesTypeError. - Avoid decorating instance methods directly: Caching
selfretains strong references to instances and prevents garbage collection.
REPL Inspect
from functools import cache
help(cache)
Linked from
- tuts/python3/stdlib_module/functools
- tuts/python3/stdlib_module/functools/cached_property
- tuts/python3/stdlib_module/functools/cmp_to_key
- tuts/python3/stdlib_module/functools/lru_cache
- 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/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/lru_cache 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