The Python lru_cache() function is a decorator that wraps a function with a callable object, which calls the function more efficiently during the input operations with the same arguments. This caches the result of the recent maxsize calls. LRU is an abbreviation called Least Recently Used.
This function has a default maximum size of 128, and it will specify the most number of recent calls to be cached.
SyntaxFollowing is the syntax for the lru_cache() function.
lru_cache(maxsize = 128, typed = False)Parameters
The parameters for the lru_cache() function are listed below −
This function returns the decorated function that wraps the original metadata.
Example 1In the example below, we are finding the number of vowels in a given string using the lru_cache() function with the specified maximum size.
from functools import lru_cache @lru_cache(maxsize = 110) def count_vowels(x): x = x.casefold() return sum(x.count(vowel) for vowel in 'aeiou') print(count_vowels("Welcome to Turoialspoint"))Output
The result is generated as follows −
10Example 2
Now, we are calculating Fibonacci sequence numbers using lru_cache(), where the sequence starts from 0 and 1, and each subsequent number is the sum of the previous numbers.
from functools import lru_cache @lru_cache(maxsize=100) def fib(x): if x < 4: return x return fib(x-2) + fib(x-1) print(fib(20))Output
The code is generated as follows −
10946Example 3
In this example, we are using the lru_wraps() function to demonstrate the performance by caching results while calculating the sum of a numbers's digits in base 20.
from functools import lru_cache @lru_cache(maxsize=100) def sum(x): if x == 0: return 0 return x % 20 + sum(x // 20) print(sum(2398564))Output
The output is obtained as follows −
61
python_modules.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4