lru_cache() function from Python's functools module is used to cache the results of function calls. When the same function is called again with the same arguments, the stored result is returned instead of executing the function again.
Example: The following example caches the result of a function call so that repeated calls with the same argument reuse the stored result.
from functools import lru_cache
@lru_cache()
def square(n):
print("Calculating...")
return n * n
print(square(5))
print(square(5))
Output
Calculating... 25 25
Explanation:
- first call to square(5) executes the function and stores the result in the cache.
- second call uses the cached result. Therefore, "Calculating..." is printed only once.
Syntax
@lru_cache(maxsize=128, typed=False)
Parameters:
- maxsize: Maximum number of function results stored in the cache. The default value is 128. Use None for an unlimited cache size.
- typed: If True, arguments of different types are cached separately. For example, f(3) and f(3.0) are treated as different calls.
Examples
Example 1: The Fibonacci sequence contains many repeated calculations. Using lru_cache() stores previously computed values and avoids recalculating them.
from functools import lru_cache
@lru_cache()
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(30))
Output
832040
Explanation:
- @lru_cache() stores the result of each fib(n) call.
- When the same value is needed again, the cached result is returned.
- This avoids repeated recursive calculations.
Example 2: This example caches the vowel count for previously processed strings.
from functools import lru_cache
@lru_cache(maxsize=100)
def count_vowels(s):
s = s.lower()
return sum(s.count(v) for v in "aeiou")
print(count_vowels("Welcome to GeeksforGeeks"))
print(count_vowels("Welcome to GeeksforGeeks"))
Output
9 9
Explanation:
- first call calculates the vowel count and stores the result.
- second call uses the cached value.
- count_vowels() does not need to process the string again.
Example 3: This example uses lru_cache() to store factorial values computed through recursion.
from functools import lru_cache
@lru_cache()
def fact(n):
if n <= 1:
return 1
return n * fact(n - 1)
print(fact(6))
Output
720
Explanation:
- fact(n) stores previously computed factorial values.
- Recursive calls such as fact(5), fact(4) and others are cached.
- Future calls with the same arguments can reuse these stored results.