Python › functools & Functional Programming Tools
What is functools.cached_property and how does it differ from @property combined with manual caching?
AdvancedAnswer
cached_property computes a value once on first access and stores it in the instance's __dict__ under the same attribute name, replacing itself so subsequent lookups skip the descriptor entirely and hit the cached value directly -- faster than a property that manually checks a cache flag each call. It requires the instance to support attribute assignment (no __slots__ conflict).
from functools import cached_property
class Report:
def __init__(self, data):
self.data = data
@cached_property
def summary(self):
print('Computing...')
return sum(self.data)
r = Report([1,2,3])
print(r.summary) # Computing... 6
print(r.summary) # 6 (no recompute)Real-world example A data model class uses cached_property to lazily compute an expensive aggregate statistic only when first requested by a report view.