Python › Descriptors & Properties
How would you implement a lazy, cached property using a custom descriptor (or functools.cached_property) that only computes its value once?
AdvancedAnswer
functools.cached_property computes the decorated method's value on FIRST access, then STORES the result directly in the instance's __dict__ (overriding further descriptor-based lookups for that name, since instance __dict__ takes priority for non-data descriptors) — subsequent accesses skip recomputation entirely, unlike @property which recomputes every single time.
from functools import cached_property
class DataProcessor:
def __init__(self, data):
self.data = data
@cached_property
def expensive_summary(self):
print("Computing...")
return sum(self.data) / len(self.data)
dp = DataProcessor([1, 2, 3, 4, 5])
print(dp.expensive_summary) # 'Computing...' printed, then 3.0
print(dp.expensive_summary) # 3.0, NO 'Computing...' -- cached from __dict__Real-world example Caching an expensive, rarely-changing computed value (like a parsed configuration or aggregated statistic) on first access.