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
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 """
19
20
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
30 """An object with methods to save and restore.
31
32 Unpickleable attributes will simply be deleted from the object.
33 """
34
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
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
63 if v is self:
64 del sdict[k]
65 continue
66
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
78
80 """Unpickle."""
81 self.__dict__.update(dict)
82