In Python automation, how do I use caching?

Caching in Python automation can significantly speed up the execution of repetitive tasks. By storing results of expensive function calls and reusing them when the same inputs occur again, you can save time and resources. This technique is particularly useful in data processing, web scraping, and API calls where the same data is often requested multiple times.
caching, automation, Python, performance optimization, memory storage

# Example of caching in Python using functools.lru_cache
from functools import lru_cache

@lru_cache(maxsize=None)  # Cache unlimited number of calls
def expensive_function(param):
    # Simulate an expensive computation
    print("Calculating...")
    return param * 2

# Calling the function
result1 = expensive_function(5)  # This will calculate and cache the result
result2 = expensive_function(5)  # This will retrieve the result from the cache

print(result1)  # Output: 10
print(result2)  # Output: 10 (retrieved from cache)
    

caching automation Python performance optimization memory storage