Last active
August 17, 2018 18:56
-
-
Save jmetz/93a7bee657efc1826add676ae7f68d3b 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 | |
print("THIS IS ON GITHUB AT:") | |
print("https://gist.github.com/jmetz/93a7bee657efc1826add676ae7f68d3b/") | |
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: | |
raise TypeError("This function has been decorated as using `save_result`; you must specify the additional keyword argument %s" % savekey) | |
if os.path.isfile(fname): | |
result = loader(fname) | |
else: | |
result = func(*args, **kwargs) | |
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") | |
print("Error anyway:") | |
traceback.print_exc() | |
print("REMEMBER THAT WAS FINE / EXPECTED") | |
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