Created
February 5, 2018 09:42
-
-
Save gregoryvit/91fe47c4a4b39f10c4e67caf4aae0cec to your computer and use it in GitHub Desktop.
Revisions
-
gregoryvit created this gist
Feb 5, 2018 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,6 @@ 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 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,32 @@ 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