76. Using functools.lru_cache
1. Basic Caching with lru_cache
lru_cacheimport 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 result2. Caching with maxsize
maxsizeimport 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 33. Using lru_cache on Recursive Functions
lru_cache on Recursive Functions4. Checking Cache Statistics
5. Clearing the Cache with cache_clear
cache_clear6. Custom Cache Size
7. Using lru_cache with Keyword Arguments
lru_cache with Keyword Arguments8. Caching Functions with No Arguments
9. Working with Immutable Arguments for Caching
10. Using lru_cache with Function Wrapping
lru_cache with Function WrappingLast updated