Package cosmolopy :: Module saveable

Source Code for Module cosmolopy.saveable

 1  """A Saveable class with methods to save and restore. 
 2   
 3  Saveable is designed to be subclassed to create new types of objects 
 4  that can easily be pickled and reloaded. 
 5  """ 
 6   
 7  import pickle 
 8   
9 -class NullWriter:
10 """Dummy file-like object that does nothing. 11 12 From 13 http://stackoverflow.com/questions/1809958/hide-stderr-output-in-unit-tests 14 15 Used in Saveable. 16 """
17 - def write(self, s):
18 pass
19 20
21 -def loadSaveable(filename):
22 """Return an instance of an object unpickled from a file. 23 """ 24 picfile = open(filename) 25 loaded = pickle.load(picfile) 26 picfile.close() 27 return loaded
28
29 -class Saveable(object):
30 """An object with methods to save and restore. 31 32 Unpickleable attributes will simply be deleted from the object. 33 """ 34
35 - def __init__(self, filename=None):
36 if filename is not None: 37 self.load(filename)
38
39 - def save(self, filename):
40 """Save object to a file.""" 41 picfile = open(filename, 'w') 42 pickle.dump(self, picfile) 43 picfile.close()
44
45 - def load(self, filename):
46 """Return an instance of an object unpickled from a file. 47 """ 48 picfile = open(filename) 49 loaded = pickle.load(picfile) 50 picfile.close() 51 self.__dict__.update(loaded.__dict__) 52 return self
53
54 - def dumb_pickle_filter(self):
55 """Filter out attributes that can't be pickled. 56 57 Returns a copy of dict with 58 """ 59 picfile = NullWriter() 60 sdict = self.__dict__.copy() 61 for k, v in sdict.items(): 62 # Avoid self references (and thereby infinite recurion). 63 if v is self: 64 del sdict[k] 65 continue 66 # Remove any attributes that can't be pickled. 67 try: 68 pickle.dump(v, picfile) 69 except (TypeError, pickle.PicklingError) as err: 70 if hasattr(self, 'verbose') and self.verbose: 71 print "Won't pickle", k, type(v), ": " 72 print "'", err, "'" 73 del sdict[k] 74 return sdict
75 - def __getstate__(self):
76 """Prepare a state of pickling.""" 77 return self.dumb_pickle_filter()
78
79 - def __setstate__(self, dict):
80 """Unpickle.""" 81 self.__dict__.update(dict)
82