cached_property Computes Once Per Instance
Cache expensive per-instance results with cached_property: the first access computes, later reads reuse the stored value without recomputation.
Code
from functools import cached_property
class Report:
def __init__(self, numbers):
self.numbers = numbers
self.computations = 0
@cached_property
def stats(self):
# 假装这是一次昂贵的聚合:只在首次访问时执行
self.computations += 1
return sum(self.numbers) / len(self.numbers)
report = Report([3, 9, 12, 4])
first = report.stats
second = report.stats
print('value :', first)
print('same cached:', first is second)
print('computed :', report.computations, 'time(s)')Output
Captured from a sandboxed run of this snippet in the build pipeline.
value : 7.0
same cached: True
computed : 1 time(s)How it works
Count the class Report and the functions __init__ and stats as the entire surface area of cached_property Computes Once Per Instance.
Putting it to use
Signature: def stats(self)
Running the file prints labeled results such as value :, same cached:, computed : — each operation’s effect is visible in the output.
stats is what another module would consume; nothing else here is load-bearing for callers.
Core lines
def __init__(self, numbers):
self.numbers = numbers
self.computations = 0
def stats(self):
# 假装这是一次昂贵的聚合:只在首次访问时执行
self.computations += 1
return sum(self.numbers) / len(self.numbers)
Interactive Tools for This Topic
Cache-Control BuilderCompose a valid Cache-Control header from directives such as no-store, private, max-age, and immutable.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. Every import resolves inside the standard library — `functools`. The file defines `__init__`, `stats` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.