__getstate__ and __setstate__

Muppet google.com at magicdb.com
Sat Mar 8 23:24:15 EST 2003


> Nevertheless, you know your code better than I.  If pickling a dict
> won't do, then you can work around the limitation of shelve using the
> __getstate__ and __setstate__ methods.  I will be happy to elaborate
> if you wish.

So I took an initial crack at this:

To the code earlier, add:

        def __getstate__(self):
                return self.__dict__
        def __setstate__(self, state):
                global known
                for x in range(0,len (state['submuppet'])):
                        m = state['submuppet'][x]
                        if known.has_key(m.id):
                                state['submuppet'][x] = known[m.id]
                        else:
                                known[m.id] = m
                self.__dict__ = state

where "known" is a global array

This *works*, leaving aside various evils associated with IDs
colliding with eachother, etc. But it's not very general. I'd like to
be able to automagically test every object being restored from the
pickle, see if we have it already, and if so, us that instead.

It seems like the Pickle module might be able to do something like
this using the "persistent_id" features for *all* objects... somehow
indicate that everything is external? Then restore?

I don't know. It all seems tantalizingly close to orthogonal
persistence, but I just can't quite figure it out.




More information about the Python-list mailing list