Created
March 23, 2012 20:33
-
-
Save stober/2174684 to your computer and use it in GitHub Desktop.
Pickle Expensive Computations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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