[Grok-dev] model not getting persisted

Lennart Regebro regebro at gmail.com
Fri Mar 23 04:18:26 EDT 2007


On 3/23/07, Tim Terlegård <tim at se.linux.org> wrote:
> On Thu, Mar 22, 2007 at 07:41:13PM -0300, Fernando Correa Neto wrote:
> > Hi,
> >
> > On 3/22/07, Tim Terlegård <tim at se.linux.org> wrote:
> > >If I have a model like this the x variable won't survive a server
> > >restart.
> > >
> > >class MyModel(grok.Model):
> > >    x = PersistentList()
> > >
> >
> > I don't think it works even in a plain zope3.
>
> I haven't tried this particular example, I just remember I've seen code
> similar to this.
>
> Check for instance how lastName etc are initialized in the Contact class
> here: http://dc.ubuntu-us.org/bazaar/zope3class/html/lesson03/index.html
>
> and how fullname is initialized here:
> http://wiki.zope.org/zope3/HowDoIModifyAnExistingPersistentObject
>
> I'm obviously missing something here as I'm confused, please enlighten
> me  :)
I tried to write an explanation, but failed. So I'll explain with
code, and hop it explains it:

>>> class Foo:
...   bar = []
...
>>> foo1 = Foo()
>>> foo2 = Foo()
>>> foo1.bar is foo2.bar
True
>>>
>>> foo1.bar.append(1)
>>> foo2.bar
[1]
>>> foo1.bar is foo2.bar
True
>>>
>>> foo1.bar = [2]
>>> foo2.bar
[1]
>>> foo1.bar is foo2.bar
False
>>>
>>> Foo.bar = [2]
>>> foo2.bar
[2]
>>> foo1.bar is foo2.bar
False

In the first case you are modifying an object set as an attribute on
the class. In the second case you are setting an attribute on the
instance.

Basically, this is a variation of the classic

def frotz(foo, bar=[]):
 bar.append(foo)

mistake. Don't use mutable objects as defaults in functions or as
class variables. You'll end up modifying the default instead of
overriding it.

-- 
Lennart Regebro: Zope and Plone consulting.
http://www.colliberty.com/
+33 661 58 14 64


More information about the Grok-dev mailing list