I want to come up with a simple convenience function to save and load pickle objects. A secondary objective is to simply execute the function without the above function. I have come up with two versions so far. Just want some opinions, which of the following will be better from a software engineering point of view. Or more pythonic. If possible please suggest a still better version, with changed parameter names or something already out there.
def test(filename, func, exec_only=False, ignore_file=False, **kwargs): if exec_only: obj = func(**kwargs) else: fname = Path(filename) if fname.exists() and not ignore_file: obj = jl.load(filename) else: obj = func(**kwargs) jl.dump(obj, fname, compress=True) return obj
def test2(filename, func, exec_only=False, ignore_file=False, **kwargs): if Path(filename).exists() and not ignore_file and not exec_only: obj = jl.load(filename) else: obj = func(**kwargs) if not exec_only: jl.dump(obj, fname, compress=True) return obj
Thanks a lot in advance.
EDIT: I created this function as a machine learning utility, since execution is typically very costly and the decision to execute is dependent on the presence of the file. I will be incorporating some features from Sam's answer. Thanks.