[ZODB-Dev] __setstate__
Jeremy Hylton
jeremy@zope.com
Thu, 28 Mar 2002 14:06:25 -0500
>>>>> "ML" == Magnus Lyck <Magnus> writes:
ML> I have a number of classes that subclass Persistence.Persistent.
ML> I want to upgrade attributes for some of them, and understand
ML> that I should do this in __setstate__.
ML> Can someone give an example of how to do this?
There is an example in the StandaloneZODB release. See the
__getstate__() and __setstate__() methods defined on
PersistentMapping.
ML> Do I need to call __setstate__ of a base class
ML> (Persistence.Persistent) in my own __setstate__?
No. The Persistent __setstate__ implementation accepts a dictionary
and assign all its items as attributes of the instance. Presumably,
you'll want to do something different with some or all of the
attributes, so you don't what the default implementation to be invoked.
ML> Should I do something about __getstate__ as well?
Probably.
ML> Are there any particular gotchas or better alternatives?
The comment in PersistentMapping explains some gotchas. If you have
persistent objects and you want a database to be shared between
clients running the old code and clients running the new code, your
getstate and setstate must always create state objects that the old
code will understand correctly. Depending on the changes, this may
not be possible.
In the case of PersistentMapping, it is possible because the change in
PersistentMapping was very simple -- just a change of attribute name.
The new code writes pickles in the format used by the old code.
Feel free to post more specific questions once you get started. Many
of the getstate/setstate issues are not ZODB specific, so you may find
helpful answers on comp.lang.python, too.
Jeremy