193. Caching with functools

The functools module in Python provides several utilities to help with function decorators, and one of the most useful features is caching, which helps optimize the performance of functions by storing previously computed results. The functools.cache functions (lru_cache, cache_property, cache_on_self) are specifically designed for this purpose.

Here are 10 Python code snippets that demonstrate how to use caching with functools to improve the performance of various functions:


1. Basic Caching with lru_cache

Copy

from 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 result

2. Caching with maxsize Parameter

Copy

from 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 evicted

3. Clearing Cache Manually

Copy


4. Using cache_property for Cached Properties

Copy


5. Using Cache with Mutable Arguments

Copy


6. Caching with Functions that Have Default Arguments

Copy


7. Using cache_on_self for Method Caching

Copy


8. Performance Boost with Cache for Recursion

Copy


9. LRU Cache with Custom Key Function

Copy


10. Handling Cache Misses with Default Values

Copy


In these snippets:

  1. lru_cache(maxsize) is used for caching results of functions with positional and keyword arguments.

  2. cached_property caches the result of a method call as a property, avoiding recomputation.

  3. The cache size can be controlled with the maxsize parameter, and the cache can be cleared manually using cache_clear().

  4. Caching significantly boosts performance when dealing with expensive or recursive computations by avoiding redundant calculations.

Last updated