Make code faster with cached_property

Posted by Afsal on 16-Sep-2022

Hi Pythonistas!

Today we will learn a method for caching properties of a class , which cached_property of functools module.This will increase the performance. This function is called only once. Next time onward results are taken from the cache. Let's learn by an example

Code

from functools import cached_property

class A:
   a = 1
   b = 2

   @property
   def normal_property(self):
        print("Inside normal property")
        return self.a + self.b

   @cached_property
   def cachedproperty(self):
       print("Inside cached property")
       return self.a + self.b

a = A()
for i in range(5):
    print(a.normal_property)
    print(a.cachedproperty)

Output

Inside normal property
3
Inside cached property
3
Inside normal property
3
3
Inside normal property
3
3
Inside normal property
3
3
Inside normal property
3
3

If we check the output “Inside cached property” is printed only once. This means that function is called once but we get the required result. If the computation is very large this very good option to use. Now we can check the performance change in both functions. 

Note: Before using timeit I have removed the print

Code

import timeit

a = A()

def call_normal():
    global a
    return a.normal_property

def call_cached():
    global a
    return a.cachedproperty

time_for_normal = timeit.timeit(call_normal, number=1000_000)
print("Time taken for property: ",time_for_normal)

time_for_cached = timeit.timeit(call_cached, number=1000_000)
print("Time taken for cached: ",time_for_cached)

Output

Time taken for property:  0.1328671849996681

Time taken for cached:  0.05630743700021412

As expected the cached property is much faster than the property

Hope you have learned something from this post. Please share your feedback and topic suggestions with afsal@parseltongue.co.in