What is the cached_property decorator module in Python?
The functools module in Python
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.
The cached_property decorator
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.
Syntax
@cached_property
Parameters
The decorator has no parameters.
Code
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)
Explanation
-
Line 1: We import relevant methods and decorator from
functoolspackage. -
Lines 3–16: We define a class called
ListProductthat has two methods calledproductandproduct_of_elements. Both methods calculate the product of the elements inlst.product_of_elementsmethod is decorated with@cached_propertydecorator. -
Line 19: We create an instance of
ListProductclass calledListProductObject. -
Lines 20 to 26: The
productis invoked onListProductObjecttwo times. Every time the method is invoked, the product of the elements inlstis calculated. We can verify this by checking whether the print statement in theproductmethod is executed every time the method is called. -
Lines 28 to 33: We invoke the
product_of_elementsonListProductObjectas a property two times. The first time the property is accessed, theproduct_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 theproduct_of_elementsmethod is executed every time the method is called.
Note: Refer How to use the reduce() method in Python to learn more about the
reducemethod.