Question

Confusion about Caching with Decorators in Python

I'm working with Python decorators to implement caching for functions. I understand the basic concept of caching results to improve performance, but I'm struggling with how to handle different function arguments and ensure the cache updates when the underlying data changes.

I've implemented a basic decorator that stores function results in a dictionary based on arguments. However, this approach doesn't handle situations where the function arguments might have complex structures (like nested lists) or when the underlying data the function relies on might be modified.

def simple_cache(func):
  cache = {}
  def wrapper(*args, **kwargs):
    key = (args, kwargs)  # Basic key based on arguments
    if key not in cache:
      cache[key] = func(*args, **kwargs)
    return cache[key]
  return wrapper

@simple_cache
def calculate_something(data):
  # Simulates complex calculation
  # ...
  return result
 2  44  2
1 Jan 1970