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 method
1from functools import cached_property
# Import time for simulating slow computation
2import time
3
# ExpensiveCalculation has a slow computation
# We want to avoid recalculating the result
4class ExpensiveCalculation:
# __init__ stores the input value
5 def __init__(self, value: int):
6 self.value = value
7
# @cached_property computes once, caches result
# Subsequent accesses return cached value
8 @cached_property
# result is the expensive property
# Return type is int
9 def result(self) -> int:
# Print to show when computation happens
10 print("Computing...")
# Simulate slow operation
11 time.sleep(0.1)
# Return squared value
12 return self.value ** 2
13
# Create instance with value 5
14obj = 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..." printed
16print(f"Second: {obj.result}")
# Third access also uses cached value
# Still no "Computing..." printed
17print(f"Third: {obj.result}")

Output

Computing...
First: 25
Second: 25
Third: 25
Practice typing this code

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

More Python examples at level 5

← Python typing practice