Caching or memoization is the act of storing calculated results in order to avoid having to calculate them again. In Python we have the @cache decorator in the functools module. But I figured it would be fun to write my own. I know it's silly but its also fun to see how a simple implementation of a cache actually works... Its basically just a dictionary with the function name plus its parameters as the key looking up the calculated value.
@my_cache
cache = {}
def my_cache(func):
def wrapper(*args, **kwargs):
key = f'{func.__name__}-{args}-{kwargs}'
if key in cache:
return cache[key]
result = func(*args, **kwargs)
cache[key] = result
return result
return wrapper
# How to use it
@my_cache
def try_my_cache(*args, **kwargs):
time.sleep(3)
return 'This result will just have to wait 3 seconds once.'