LRU cache python using functools : Implementation in two lines Stepwise

LRU cache python using functools

lru cache python is helpful in speed up a python module which is repetitive. It helps in saving computational time for repetitive functions.

In many scenarios, where we have any python function which is repetitive. Here if we compute it every time, It will add no value. Because the output of the function will be the same always. Here if we apply lru cache python, It will memorize the output of the function. Hence when we call the same function with the same input, It will not compute it. In the place of that, It will return the memorize the output.

lru cache python Implementation using functools-

There may be many ways to implement lru cache python. In this article, we will use functools python module for implementing it.

Step 1:

Importing the lru_cache function from functool python module.

from functools import lru_cache

Step 2:

Let’s define the function on which we need to apply the cache. Here is the function which calculates the cube of the given parameter.

def tansformer(num):
  result=num*num*num
  return result

Step 3:

Let’s apply the decorator for lru cache over the function.

@lru_cache(maxsize = 150)
def tansformer(num):
  result=num*num*num
  return result

Here maxsize = 150 parameter defines the max memory size for function. It means it applies the LRU cache algorithm over the last 150 function calls only. You may specify the value as per the requirement.

Complete Code –

We have understood the full lru implementation in python in steps. Let’s integrate them at a place.

from functools import lru_cache 
# cache function
@lru_cache(maxsize = 100) 
def tansformer(num):
  result=num*num*num
  return result
#print function
print(tansformer(10021))

Let’s run see the output.

"<yoastmark

 

Conclusion –

lru cache works awesome when the function is complex and we invoke it frequently. It can save a lot of computation time and power. Well, I hope this article must solve all your doubts over lru cache using functools. I have tried my best to simplify this implementation but still if you think we can improve it. Please comment below.

 

Thanks
Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Abhishek ( Chief Editor) , a data scientist with major expertise in NLP and Text Analytics. He has worked on various projects involving text data and have been able to achieve great results. He is currently manages Datasciencelearner.com, where he and his team share knowledge and help others learn more about data science.
 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner