Middle
You need to implement a decorator that caches the result of a method based on its input arguments.
sobes.tech AI
Answer from AI
To implement a decorator for caching the result of a method based on input arguments in Python, you can use a dictionary to store the results. Here's an example of a simple decorator:
def cache_decorator(func):
cache = {}
def wrapper(*args, **kwargs):
key = (args, tuple(sorted(kwargs.items())))
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
return wrapper
# Example usage
@cache_decorator
def compute(x, y):
print("Calculating...")
return x + y
print(compute(1, 2)) # Calculating...
3
print(compute(1, 2)) # 3 (retrieved from cache, no recalculation)
This decorator stores the results of function calls with specific arguments and returns the cached result on subsequent calls with the same parameters.