I have a program that runs daily where there are a number of objects that a) take a while to create, b) are static for the day once they're built, so are good candidates to get pickled.
To avoid writing this a bunch of times:
if object_pickle_exists:
obj = load_pickle_object
else:
obj = run_some_function_to_build_object()
pickle(obj) for later
I am instead trying to build a pickle-based function that I can generically use to "Get/Set" variables.
Loads Pickle, otherwise runs function and pickles it
def _dill(name, function_as_an_object, date = dt.date.today()):
try:
with open('Pickles/'+name+'_'+date.strftime('%y-%b-%d'),'rb') as f:
obj = pickle.load(f)
return obj
except FileNotFoundError:
obj = function_as_an_object()
with open('Pickles/'+name+'_'+date.strftime('%y-%b-%d'),'wb') as f:
pickle.dump(obj, f)
return obj
Question 1) Is there a better way to do this / some existing package out there/
Question 2) I would like to add **kwargs to _dill(), but I'm not sure how to pass those kwargs down to the function_as_an_object:
def _dill(name, function_as_an_object, date = dt.date.today(), **kwargs):
try:
with open('Pickles/'+name+'_'+date.strftime('%y-%b-%d'),'rb') as f:
obj = pickle.load(f)
return obj
except FileNotFoundError:
obj = function_as_an_object(**kwargs) ??
with open('Pickles/'+name+'_'+date.strftime('%y-%b-%d'),'wb') as f:
pickle.dump(obj, f)
return obj