Cached Property in Python
Level 5355 keystrokes
This uses @cached_property to cache expensive computations. The property is calculated once and stored in the instance.
Python code
# Import cached_property from functools# Caches the return value of a property method1from functools import cached_property# Import time for simulating slow computation2import time3 # ExpensiveCalculation has a slow computation# We want to avoid recalculating the result4class ExpensiveCalculation: # __init__ stores the input value5 def __init__(self, value: int):6 self.value = value7 # @cached_property computes once, caches result # Subsequent accesses return cached value8 @cached_property # result is the expensive property # Return type is int9 def result(self) -> int: # Print to show when computation happens10 print("Computing...") # Simulate slow operation11 time.sleep(0.1) # Return squared value12 return self.value ** 213 # Create instance with value 514obj = ExpensiveCalculation(5)# First access computes and caches result# Prints "Computing..." then "First: 25"15print(f"First: {obj.result}")# Second access uses cached value# No "Computing..." printed16print(f"Second: {obj.result}")# Third access also uses cached value# Still no "Computing..." printed17print(f"Third: {obj.result}")Output
Computing... First: 25 Second: 25 Third: 25
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
.× 10"× 8(× 8)× 8:× 7_× 6{× 3}× 3*× 2=× 2