[Zope3-dev] Do not serialize one attribute
Jeff Shell
eucci.group at gmail.com
Thu Dec 14 18:13:10 EST 2006
On 12/14/06, Florian Lindner <mailinglists at xgm.de> wrote:
> Hello,
> I have a object, derived from Persistent when contain one attribute which is
> not serializable and that's not a problem for me, but Zope complains about
> that.
> Can I mark this attribute somehow as "not to serialize" and make Zope call a
> member function when it has unserialized this object so I can reinstantiate
> this attribute?
What do you need to do to re-instatiate the attribute? As another
reply mentioned, you can use the Python property descriptor in
combination with an `_v_` attribute. The ZODB will not serialize an
attribute whose name starts with _v_ (v means "volatile").
Alternatively, you can override ``__getstate__()`` and ``__setstate()__``
http://www.python.org/doc/2.4/lib/pickle-inst.html
Classes can further influence how their instances are pickled; if the
class defines the method __getstate__(), it is called and the return state
is pickled as the contents for the instance, instead of the contents of
the instance's dictionary. If there is no __getstate__() method, the
instance's __dict__ is pickled.
Upon unpickling, if the class also defines the method __setstate__(), it
is called with the unpickled state.13.5 If there is no __setstate__()
method, the pickled state must be a dictionary and its items are assigned
to the new instance's dictionary. If a class defines both __getstate__()
and __setstate__(), the state object needn't be a dictionary and these
methods can do what they want.
So let's say that the name of this particular attribute is
'unserializable'. You'd remove it from the 'state' dictionary returned
by 'getstate', and add it back in during 'setstate'.
Warning: It's been a long time, I think, since I've used these
methods. There may be better practices.
::
class Example(Persistent):
... (other code)
def __getstate__(self):
state = super(Example, self).__getstate__()
# you _might_ want to add '.copy()' to the above to play safe.
if 'unserializable' in state:
del state['unserializable']
# Alternatively, you might want to store a tuple or some way
# of restoring the unserializable object if you can. Some
# kind of small memento.
# This is what gets pickled and stored in the ZODB.
return state
def __setstate__(self, state):
# here is where you can re-instantiate 'unserializable'
state['unserializable'] = unserializableReinstantiationCode()
super(Example, self).__setstate__(state)
--
Jeff Shell
More information about the Zope3-dev
mailing list