Skip to content

Instantly share code, notes, and snippets.

@stober
Created March 23, 2012 20:33
Show Gist options
  • Save stober/2174684 to your computer and use it in GitHub Desktop.
Save stober/2174684 to your computer and use it in GitHub Desktop.
Pickle Expensive Computations
import cPickle as pickle
import bz2
def load_or_compute(method, filename, recompute=False):
try:
if recompute: raise Exception
fp = bz2.BZ2File(filename)
return pickle.load(fp)
fp.close()
except:
if recompute is True:
print "Recompute is True! Recomputing all data in file %s." % filename
else:
print "Error reading file: %s. Recomputing all data." % filename
fp = bz2.BZ2File(filename, "w")
item = method()
pickle.dump(item, fp, pickle.HIGHEST_PROTOCOL)
fp.close()
return item
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment