Trying to understand += better

Lie Ryan lie.1296 at gmail.com
Mon Nov 23 02:31:42 EST 2009


Roy Smith wrote:
> In article <4b0a01aa$1 at dnews.tpgi.com.au>, Lie Ryan <lie.1296 at gmail.com> 
> wrote:
> 
>> The semantic of the in-place operator is something like:
>> x += y
>> becomes
>> x = x.__iadd__(y)
>>
>> thus
>> foo.bar += baz
>> becomes
>> foo.bar = foo.bar.__iadd__(baz)
>>
>> So the call sequence is,
>> foo.__getattr__('bar') ==> x
>> x.__iadd__(baz) ==> y
>> foo.__setattr__('bar', y)
> 
> I don't get where the __setattr__() call comes from in this situation.  I 
> thought the whole idea of __iadd__(self, other) is that it's supposed to 
> mutate self.  So, why is there another assignment happening after the 
> __iadd__() call?

The formal name of the __iop__ is "agumented assignment". The name 
doesn't talk about in-place; but it does talk about assignment. The 
semantic defines that augmented assignment operation is done in-place 
*when the left-hand side object supports it* (i.e. it does not require 
in-place mutation).

"""
  The __iadd__ hook should behave similar to __add__, returning the 
result of the operation (which *could* be `self') which is to be 
assigned to the variable `x'.
"""

For a more complete description, see: 
http://www.python.org/dev/peps/pep-0203/



More information about the Python-list mailing list