Last active
August 9, 2021 10:59
-
-
Save Rustam-Z/7f35b70e500f1d6c71664992c2cdefe8 to your computer and use it in GitHub Desktop.
Store the results of the decorated function for fast lookup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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