Skip to content

Instantly share code, notes, and snippets.

@gilesc
Created May 7, 2021 20:17
Show Gist options
  • Save gilesc/e0d6dffd15a973ffb3ec744900cc6ce8 to your computer and use it in GitHub Desktop.
Save gilesc/e0d6dffd15a973ffb3ec744900cc6ce8 to your computer and use it in GitHub Desktop.
import functools
import time
import pickle
import os
def decorator(save_path="default"):
def wrapper(fn):
@functools.wraps(fn)
def wrap(self, *args, **kwargs):
if not os.path.exists(save_path):
o = fn(self, *args, **kwargs)
with open(save_path, "wb") as h:
pickle.dump(o, h)
with open(save_path, "rb") as h:
return pickle.load(h)
return wrap
return wrapper
class Foo(object):
@decorator(save_path="/home/gilesc/test.pkl")
def myfunc(self):
time.sleep(3)
return "xyz"
if __name__ == "__main__":
obj = Foo()
print(obj.myfunc())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment