functools.cached_property
Prev: functools.cache | Up: functools | Next: functools.cmp_to_key
Rel: functools.cache, functools.cmp_to_key, functools.lru_cache, functools.partial
Ref: docs.python.org — functools.cached_property
Tags: #public #python3 #stdlib #functools
Import
import functools
from functools import cached_property
Signature & Overview
functools.cached_property(func)
functools.cached_property class.
Usage
from functools import cached_property
class Report:
def __init__(self, values: list[int]) -> None:
self.values = values
self.computations = 0
@cached_property
def total(self) -> int:
self.computations += 1
return sum(self.values)
r = Report([10, 20, 30])
assert r.total == 60 and r.total == 60 and r.computations == 1
Gotchas
- Stores result in
instance.__dict__: Classes with__slots__(and no'__dict__'slot) cannot use@cached_property. - Writable and invalidatable: Unlike
@property,r.total = 99works, anddel r.totalclears the cached value so the next access recomputes it.
REPL Inspect
from functools import cached_property
help(cached_property)
Linked from
- tuts/python3/stdlib_module/functools
- tuts/python3/stdlib_module/functools/cache
- 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/cache 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