Created
February 5, 2018 09:42
-
-
Save gregoryvit/91fe47c4a4b39f10c4e67caf4aae0cec to your computer and use it in GitHub Desktop.
Simple decorator for results caching
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
from simple_cacher import cacheable_result | |
@cacheable_result('temp.p', needs_to_cache=False) | |
def get_data(): | |
# Some data fetching operation | |
return [1, 2, 3, 4] |
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
import pickle | |
from functools import wraps | |
def save_to_cache(file_path, object_to_cache): | |
pickle.dump(object_to_cache, open(file_path, "wb")) | |
def load_from_cache(file_path): | |
return pickle.load(open(file_path, "rb")) | |
def cacheable_result(file_path, needs_to_cache=True): | |
def decorator(retrieve_data_f): | |
@wraps(retrieve_data_f) | |
def wrapped(*args, **kwargs): | |
if needs_to_cache: | |
try: | |
result = load_from_cache(file_path) | |
except: | |
result = retrieve_data_f(*args, **kwargs) | |
save_to_cache(file_path, result) | |
else: | |
result = retrieve_data_f(*args, **kwargs) | |
save_to_cache(file_path, result) | |
return result | |
return wrapped | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment