Created
August 17, 2018 18:10
-
-
Save jmetz/4c051dd8bffb0eb2ea15ca206f303c1c to your computer and use it in GitHub Desktop.
Simple decorator to add loading and saving to a function
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
from functools import wraps | |
import pickle | |
import traceback | |
import os | |
def save_result(func, | |
loader=lambda fname: pickle.load(open(fname, "rb")), | |
saver=lambda obj, fname: pickle.dump(obj, open(fname, "wb")), | |
savekey="filename", | |
): | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
if savekey in kwargs: | |
fname = kwargs.pop(savekey) | |
else: | |
# Should now generate output filename based on hash of arguments | |
# and something related to the function name (I guess) | |
raise NotImplementedError("CODE ME") | |
if os.path.isfile(fname): | |
result = loader(fname) | |
else: | |
result = func(*args, **kwargs) | |
print("IN WRAPPER; RESULT:", result) | |
print("CALLING SAVER") | |
saver(result, fname) | |
return result | |
return wrapper | |
@save_result | |
def should_not_work(a,b): | |
print("RUNNING should_not_work") | |
return a + b | |
@save_result | |
def should_work(a,b): | |
print("RUNNING should_work") | |
return a + b | |
if __name__ == '__main__': | |
try: | |
should_not_work(10,20) | |
except: | |
print("Good :) That wasn't supposed to work") | |
try: | |
print(should_work(100,100, filename="testfile.pkl")) | |
print(should_work(100,100, filename="testfile.pkl")) | |
print(should_work(100,100, filename="testfile.pkl")) | |
except: | |
print("Damn, that should have worked") | |
traceback.print_exc() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment