Using cachetools for caching in Python

cachetools is a small yet powerful library for caching that provides various caching strategies, such as LRU (Least Recently Used), LFU (Least Frequently Used), and others. It helps optimize performance by avoiding repeated computations or requests.

cachetools is useful when you need to store temporary results or intermediate data to improve performance.

from cachetools import cached, LRUCache

# Create an LRU cache with a maximum size of 3
cache = LRUCache(maxsize=3)

@cached(cache)
def expensive_computation(x):
    print(f"Performing complex computation for {x}")
    return x * x

# Example usage
print(expensive_computation(2))  # Computation is performed
print(expensive_computation(2))  # Result is obtained from the cache

# Output:
# Performing complex computation for 2
# 4
# 4

Comments (0)

Leave a comment