-
-
Save manugarri/2433a22600dd705f542d6589b097ba91 to your computer and use it in GitHub Desktop.
Persisting a cache in Python to disk using a decorator
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 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment