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.
Importing the lru_cache function from functool python module.
from functools import lru_cache
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
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.
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.
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.