Created
February 17, 2017 15:33
-
-
Save jorgecarleitao/c9725373c04896e7b62e8f6f5c0ca657 to your computer and use it in GitHub Desktop.
A decorator of functions that stores a dictionary *args->result in a pickle and returns cached versions after first call
This file contains hidden or 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
import os | |
import pickle | |
def cache(file_name): | |
""" | |
A decorator to cache the result of the function into a file. The result | |
must be a dictionary. The result storage is in pickle | |
""" | |
def cache_function(function): | |
cache = {} | |
if os.path.exists(file_name): | |
# print('reading cache file') | |
with open(file_name, 'rb') as f: | |
cache = pickle.load(f) | |
def func_wrapper(*args, **kwargs): | |
unique = (repr(args), repr(tuple(kwargs))) | |
if unique not in cache: | |
# print('update cache') | |
cache[unique] = function(*args, **kwargs) | |
# update the cache file | |
with open(file_name, 'wb') as f: | |
pickle.dump(cache, f) | |
else: | |
# print('using cache file') | |
pass | |
return cache[unique] | |
return func_wrapper | |
return cache_function | |
if __name__ == '__main__': | |
@cache('bla.pkl') | |
def bla(a, b): | |
return a + b | |
bla(1, 2) # store result in 'bla.pkl' | |
bla(1, 2) # return cached result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment