Skip to content

Instantly share code, notes, and snippets.

@tohyongcheng
Last active June 20, 2016 05:29
Show Gist options
  • Save tohyongcheng/94ca536b0a5c96c9751b82150f20c95a to your computer and use it in GitHub Desktop.
Save tohyongcheng/94ca536b0a5c96c9751b82150f20c95a to your computer and use it in GitHub Desktop.
Persisting a cache in Python to disk using a decorator
def persist_cache_to_disk(filename):
def decorator(original_func):
try:
cache = pickle.load(open(filename, 'r'))
except (IOError, ValueError):
cache = {}
atexit.register(lambda: pickle.dump(cache, open(filename, "w")))
def new_func(*args):
if tuple(args) not in cache:
cache[tuple(args)] = original_func(*args)
return cache[args]
return new_func
return decorator
# example use of the decorator
@persist_cache_to_disk('users.p')
def get_all_users():
# your method here
pass
@shantanuo
Copy link

shantanuo commented Jun 18, 2016

This works from python command prompt. But it does not work from ipython notebook. A modified version can be found here.. https://gist.github.com/shantanuo/c6a376309d6bac6bd55bf77e3961b5fb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment