The functools module in Python is used to create higher-order functions that interact with other functions. The higher-order functions either return other functions or operate on them to broaden the scope of the function without modifying or explicitly defining them.
cached_property
is a decorator that converts a class method into a property whose value is calculated once and then cached like a regular attribute. The cached value will be available until the object or the instance of the class is destroyed.
@cached_property
The decorator has no parameters.
from functools import cached_property, reduceclass ListProduct:lst = []def __init__(self):self.lst = [1, 2, 3, 4, 6, 9]def product(self):print("product() method called.")return reduce(lambda x, y: x * y, self.lst)@cached_propertydef product_of_elements(self):print("product_of_elements() method called.")return reduce(lambda x, y: x * y, self.lst)ListProductObject = ListProduct()product = ListProductObject.product()print("Product without caching - ", product)print("--"*5)product = ListProductObject.product()print("Product without caching - ", product)print("--"*5)product = ListProductObject.product_of_elementsprint("Product with caching - ", product)print("--"*5)product = ListProductObject.product_of_elementsprint("Product with caching - ", product)
Line 1: We import relevant methods and decorator from functools
package.
Lines 3–16: We define a class called ListProduct
that has two methods called product
and product_of_elements
. Both methods calculate the product of the elements in lst
. product_of_elements
method is decorated with @cached_property
decorator.
Line 19: We create an instance of ListProduct
class called ListProductObject
.
Lines 20 to 26: The product
is invoked on ListProductObject
two times. Every time the method is invoked, the product of the elements in lst
is calculated. We can verify this by checking whether the print statement in the product
method is executed every time the method is called.
Lines 28 to 33: We invoke the product_of_elements
on ListProductObject
as a property two times. The first time the property is accessed, the product_of_elements()
method is executed. The next time the same property is accessed, the cached value is served. We can verify this by checking whether the print statement in the product_of_elements
method is executed every time the method is called.
Note: Refer How to use the reduce() method in Python to learn more about the
reduce
method.