Forgive my Python noob-ism, but I have written this pattern in several other languages, and can't find a boilerplate for Python that seems... pythonic, I guess.
I want a base class that either takes a set of default parameters, or loads itself from a file. It then has a save() method that saves its instance data to the given named file.
Critically, I want to be able to modify the classes that inherit from the base class to add or remove attributes, and still have the old attributes loaded from the old files. This code appears to work (2.7):
import pickle
class Thing(object):
def __init__(self, filename=''):
self.filename = filename
if self.filename:
self._load()
def save(self):
with open(self.filename, 'wb') as f:
pickle.dump(self,f)
def _load(self):
try:
with open(self.filename, 'rb') as f:
self.__dict__.update(pickle.load(f).__dict__)
return True
except:
return False
Then the inheriting class:
class BiggerThing(Thing):
def __init__(self, filename='', x=0, y=0):
self.x = x
self.y = y
#self.whoops = 'swell'
super(BiggerThing, self).__init__(filename)
This seems to work: I can do:
t = BiggerThing('file.pickle', x=1, y=2)
t.save()
And I'll get the the proper object when I do:
t2 = BiggerThing('file.pickle')
And equally important, if I un-comment the 'self.whoops' line and load the old file, I still get back the object with x=1 and y=2, and can then save() the new object with 'whoops' set.
This just seems like it would be a common pattern for making self-loadable objects, but I haven't seen it like this and wonder if it's because it isn't very pythonic?