[ZODB-Dev] Re: false write conflicts

Tim Peters tim at zope.com
Tue Mar 2 12:04:12 EST 2004


[Casey Duncan]
>>> Augmented assignment causes a setattr on the containing object. This
>>> is the way Python works. These examples are semantically
>>> equivilant::
>>>
>>>   self.x += 1
>>>   self.x = self.x + 1
>>>   setattr(self, 'x', self.x + 1)
>>>
>>> They all cause self to be modified through __setattr__. If self is a
>>> persistent instance then it will be marked changed in all three
>>> cases above.

[John Belmonte]
>> To be more accurate, it seems like
>>
>>     foo.bar += 1
>>
>> becomes the equivalent of
>>
>>     x = foo.bar; x += 1; foo.bar = x

[Casey]
> Ok, I'm not sure how that's more accurate ;^) My example don't create
> a local variable 'x'.

That's true, and if we assume foo.bar was originally bound to an int,
they're all the same (module the 'x' business).  Else John's

    x += 1

covers a subtlety not covered in yours, that x.__add__(1) and x.__iadd__(1)
may do entirely different things, so that any spelling containing "self.x +
1" is open to exposing such a difference.  You even tell this from the byte
code <wink>:

  2           0 LOAD_FAST                0 (foo)
              3 DUP_TOP
              4 LOAD_ATTR                1 (bar)
              7 LOAD_CONST               1 (1)
             10 INPLACE_ADD
             11 ROT_TWO
             12 STORE_ATTR               1 (bar)

Without *some* instance of "+=" in the putative workalike sequence, you
won't get the INPLACE_ADD opcode.

...

>> This wrapper for Persistent.__setattr__ looks like it will suit my
>> needs:
>>
>>  class MyPersistent(Persistent):
>>    def __setattr__(self, key, val):
>>      if not (self.__dict__.has_key(key) and self.__dict__[key] is val):
>>         Persistent.__setattr__(self, key, val)

> Ugh. This is bound to bite you somewhere down the line. I'd say its
> simpler to avoid augmented assignment when you don't want the
> container marked as changed. But that's me.

Also me.  When the distinction between "mutate in place or don't" is
crucial, augmented assignment notation doesn't help, and may mislead.




More information about the ZODB-Dev mailing list