193. Caching with functools
1. Basic Caching with lru_cache
lru_cachefrom functools import lru_cache
@lru_cache(maxsize=None) # No limit on the cache size
def slow_function(x):
print("Computing...")
return x * x
# Usage
print(slow_function(5)) # Computes and caches the result
print(slow_function(5)) # Retrieves the cached result2. Caching with maxsize Parameter
maxsize Parameterfrom functools import lru_cache
@lru_cache(maxsize=3) # Cache the last 3 calls
def slow_function(x):
print("Computing...")
return x * x
# Usage
print(slow_function(1)) # Computes and caches the result
print(slow_function(2)) # Computes and caches the result
print(slow_function(3)) # Computes and caches the result
print(slow_function(4)) # Computes and caches the result, evicts oldest (1)
print(slow_function(1)) # Computes again, as 1 was evicted3. Clearing Cache Manually
4. Using cache_property for Cached Properties
cache_property for Cached Properties5. Using Cache with Mutable Arguments
6. Caching with Functions that Have Default Arguments
7. Using cache_on_self for Method Caching
cache_on_self for Method Caching8. Performance Boost with Cache for Recursion
9. LRU Cache with Custom Key Function
10. Handling Cache Misses with Default Values
Last updated