Skip to content

Instantly share code, notes, and snippets.

@Rustam-Z
Last active August 9, 2021 10:59
Show Gist options
  • Save Rustam-Z/7f35b70e500f1d6c71664992c2cdefe8 to your computer and use it in GitHub Desktop.
Save Rustam-Z/7f35b70e500f1d6c71664992c2cdefe8 to your computer and use it in GitHub Desktop.
Store the results of the decorated function for fast lookup
from functools import wraps
def memorize(func):
"""Store the results of the decorated function for fast lookup """
# Store results in a dict that maps arguments to results
cache = {}
@wraps(func)
def wrapper(*args, **kwargs):
# If these arguments haven't been seen before,
if (args, kwargs) notin cache: # Call func() and store the result.
cache[(args, kwargs)] = func(*args, **kwargs)
return cache[(args, kwargs)]
return wrapper
@memorize
def slow_function(a, b):
print('Sleeping...')
time.sleep(5)
return a + b
# First time
slow_function(3, 4)
'''
Sleeping...
7
'''
# Second time
slow_function(3, 4)
# 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment