76. Using functools.lru_cache

Here are 10 Python snippets using functools.lru_cache to demonstrate caching function results and optimizing performance:


1. Basic Caching with lru_cache

The lru_cache decorator caches the results of a function to optimize performance for expensive, repeated function calls.

import functools

@functools.lru_cache(maxsize=3)
def expensive_function(x):
    print(f"Computing {x}...")
    return x * x

print(expensive_function(2))  # First call, computes the result
print(expensive_function(2))  # Second call, returns cached result

2. Caching with maxsize

The maxsize parameter determines how many results the cache can hold. If the cache exceeds the limit, the least recently used (LRU) result is removed.

import functools

@functools.lru_cache(maxsize=2)
def square(x):
    print(f"Computing square of {x}...")
    return x * x

print(square(2))  # Computed
print(square(3))  # Computed
print(square(2))  # Cached
print(square(4))  # Computed, evicts the cache for 3

3. Using lru_cache on Recursive Functions

lru_cache is useful for caching results in recursive functions, such as computing Fibonacci numbers.


4. Checking Cache Statistics

The cache_info method can be used to view statistics on the cache's performance, such as hits, misses, and the current cache size.


5. Clearing the Cache with cache_clear

You can clear the cache manually with the cache_clear method.


6. Custom Cache Size

You can adjust the maxsize parameter to store a specific number of results in the cache.


7. Using lru_cache with Keyword Arguments

lru_cache caches function results based on both positional and keyword arguments.


8. Caching Functions with No Arguments

Even if a function doesn't take any arguments, you can still apply lru_cache to optimize repeated calls.


9. Working with Immutable Arguments for Caching

lru_cache requires that function arguments be hashable, as it uses these arguments to create a cache key.


10. Using lru_cache with Function Wrapping

You can use lru_cache as part of a custom wrapper function to add caching behavior dynamically.


These snippets demonstrate how functools.lru_cache can be used to improve performance by caching the results of functions, especially those that are called frequently with the same arguments. The decorator is versatile and works well with both simple and recursive functions, as well as handling keyword arguments.

Last updated