[Zope3-dev] class lifecycle management/missing attributes
Tres Seaver
tseaver@zope.com
01 Jul 2003 22:09:44 -0400
On Tue, 2003-07-01 at 20:59, Guido van Rossum wrote:
> > Is there an example in the Zope 3 code that illustrates a solution to
> > the following problem:
> >
> > 1 - A component of class Foo is created in the ZODB.
> >
> > 2 - Class Foo is modified, adding a new attribute in __init__:
> >
> > def __init__(self):
> > self.bar = 'some_default'
> >
> > 3 - The component in the ZODB doesn't have bar -- bad.
> >
> > How would one add bar to instances of Foo already serialized? In other
> > apps, I've handled this by adding the missing attribute in a deserialize
> > method.
> >
> > I assume there's a pattern for this, but haven't spotted anything in the
> > source.
>
> If all you want is a default with an immutable value, you can put it
> in the class instead of in __init__.
>
> Otherwise, overriding __setstate__ would be an option, but I don't
> know if it's the best practice.
__setstate__ hackery can work, but is fragile: because the object is
not marked as modified when changed by __setstate__, it doesn't get
persisted in the upgraded state. Write-on-read has scalability
problems, as well, which also tend to make 'mutate inside an accessor'
solutions unsatisfactory.
Any "automagic" fixup will tend to lead to layers of forward-conversion
cruft in the class, which obscure its real purpose; because "old"
instances may never be upgraded, it isn't ever safe in general to remove
the cruft.
Our usual practice in the case where a class-scope default won't work is
to write a script which trolls through the ZODB, converting wayward
objects as it find them. Such scripts keep the cruft in ancillary
code; not only that, one can typically discard the scripts after having
run them against each affected ZODB.
Persistence-means-never-being-able-to-forget-your-mistakes'ly,
Tres.
--
===============================================================
Tres Seaver tseaver@zope.com
Zope Corporation "Zope Dealers" http://www.zope.com