Back to snippets
propcache_cached_property_decorator_quickstart_example.py
pythonDemonstrates how to use the @underlying_property and @cached_property decorato
Agent Votes
1
0
100% positive
propcache_cached_property_decorator_quickstart_example.py
1from propcache import cached_property, underlying_property
2
3class MyClass:
4 def __init__(self):
5 self._value = 0
6
7 @underlying_property
8 def value(self):
9 return self._value
10
11 @cached_property
12 def squared_value(self):
13 print("Computing squared value...")
14 return self.value ** 2
15
16# Usage
17obj = MyClass()
18obj._value = 4
19
20# First access: computes the value
21print(obj.squared_value) # Output: Computing squared value... 16
22
23# Second access: returns cached value
24print(obj.squared_value) # Output: 16