How about with a decorator:
import os
import pickle
import functools
PICKLE = False
PICKLE_PATH = '/tmp'
def checkpoint(f):
if not PICKLE:
return f
save_path = os.path.join(PICKLE_PATH, '%s.pickle' % f.__name__)
@functools.wraps(f)
def wrapper(*args, **kwargs):
if os.path.exists(save_path):
with open(save_path, 'rb') as f:
return pickle.load(f)
rv = f(*args, **kwargs)
with open(save_path, 'wb') as f:
pickle.dump(rv, f)
return rv
return wrapper
Usage:
@checkpoint
def step1():
return do_stuff_here()
def intermediate_step():
return some_operation(step1())
@checkpoint
def step2():
return do_stuff_with(intermediate_step())
# ... and so on