[Tutor] pickle question

Kent Johnson kent37 at tds.net
Wed Sep 26 04:28:05 CEST 2007


Jeff Peery wrote:
> hello,
>  
> I have a question about the pickler. I'm using it to save objects in a 
> program of mine that I can later reload to use. I was wondering how the 
> pickle works and how it references the class module when I unpickle the 
> pickled objects. for example I save some objects using the pickler, then 
> I continue to develop my program so the class module is changed and 
> additional attributes and methods are added. What happens now when I 
> unpickle the pickled data and try to operate on it using the new methods 
> and new attributes?

The pickle docs suggest that the way to handle this is to write your own 
__setstate__() method and possibly to include a version number in the 
object or write one with a __getstate__() method.

In your example, I think you could have something like this (not tested):

def __setstate__(self, d):
   if 'name' not in d:
     d['name'] = 'bob' # some appropriate default for old pickles
   self.__dict__.update(d)

Every time you change the class data, add a bit of conversion code to 
__setstate__(). If you just keep accreting converters to the end of 
__setstate__(), it will be able to upgrade any version of pickle.

Kent

PS Please don't start a new thread by replying to another thread, create 
a new message. Those of use who use threaded mail readers will 
appreciate it.

PPS Mike Hansen please ignore the previous PS ;-)


More information about the Tutor mailing list