How do I cache expensive computations in Python?

Caching expensive computations in Python ensures that repeated function calls with the same inputs do not require the same processing time, significantly improving performance in data-driven applications.
caching, memoization, performance optimization, Python, expensive computations
# Example of caching expensive computations using functools.lru_cache
from functools import lru_cache
import time

@lru_cache(maxsize=None)  # Unlimited cache size
def expensive_computation(n):
    time.sleep(2)  # Simulate a time-consuming computation
    return n * n

# First call will take time
print(expensive_computation(4))  # Output: 16

# Subsequent call will be fast as it is cached
print(expensive_computation(4))  # Output: 16
print(expensive_computation(5))  # Output: 25
print(expensive_computation(5))  # Output: 25
    

caching memoization performance optimization Python expensive computations