Created
April 11, 2019 17:37
-
-
Save scottwallacesh/4760e51d3d0f3a1764a055b89f22c9fa to your computer and use it in GitHub Desktop.
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
def cache(func): | |
""" | |
Decorator function to cache the returned object of a function. | |
""" | |
cache_bucket = {} | |
def store_and_retrieve(*args, **kwargs): | |
""" | |
Function to store and return objects in the cache. | |
""" | |
# Handle functions with no arguments | |
if not args: | |
if not func.func_name in cache_bucket: | |
cache_bucket[func.func_name] = func() | |
return cache_bucket[func.func_name] | |
# Handle functions with arguments | |
else: | |
if not func.func_name in cache_bucket: | |
cache_bucket[func.func_name] = {} | |
if not args in cache_bucket[func.func_name]: | |
cache_bucket[func.func_name][args] = func(*args, **kwargs) | |
return cache_bucket[func.func_name][args] | |
return func(*args, **kwargs) | |
return store_and_retrieve |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment