Python functools cached_property() Function
The Python cached_property() function transforms a method of a class into a property, where its value is computed only once and this value will be cached as a normal attribute. Here, the result is stored when the method is executed for the first time.
This function improves the performance of a program by avoiding the duplicate calculations and simplifies code by allowing method.
Syntax
Following is the syntax for the function.
@cached_property()
Parameters
This function doesn't accept any parameters.
Return Value
Decorator returns the cached result from the decorated method.
Example 1
In this example, we are calculating the area of a circle using the cached_property() decorator. The result is cached, so subsequent accesses to the area returns the cached value without recalculating.
from functools import cached_property
class Circle:
def __init__(self, rad):
self.rad = rad
@cached_property
def area(self):
print("Calculating area of a circle.")
return 3.14159 * self.rad ** 2
circle = Circle(23)
print(circle.area)
print(circle.area)
Output
The result is generated as follows −
Calculating area of a circle. 1661.90111 1661.90111
Example 2
Now, we compute the total_sum of the numbers using the cached_property function. This result will be stored, so future accesses to total_sum retrieves the cached value without recalculating.
from functools import cached_property
class NumSeries:
def __init__(self, num):
self.num = num
@cached_property
def total_sum(self):
print("Sum of the numbers")
return sum(self.num)
series = NumSeries([21, 3, 12, 45, 65])
print(series.total_sum)
print(series.total_sum)
Output
The code is generated as follows −
Sum of the numbers 146 146
Example 3
In the below code, the cached_property() decorator is used to cache the result of the function, converting the lowercase letters to uppercase.
from functools import cached_property
class MyString:
def __init__(self, text):
self.text = text
@cached_property
def upper_text(self):
return self.text.upper()
s = MyString("welcome to tutorialspoint")
print(s.upper_text)
print(s.upper_text)
Output
The output is obtained as follows −
WELCOME TO TUTORIALSPOINT WELCOME TO TUTORIALSPOINT
python_modules.htm