Skip to content

Instantly share code, notes, and snippets.

@scottwallacesh
Created April 11, 2019 17:37
Show Gist options
  • Save scottwallacesh/4760e51d3d0f3a1764a055b89f22c9fa to your computer and use it in GitHub Desktop.
Save scottwallacesh/4760e51d3d0f3a1764a055b89f22c9fa to your computer and use it in GitHub Desktop.
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