Trying to understand += better
Terry Reedy
tjreedy at udel.edu
Mon Nov 30 17:35:20 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)
Except that the expression x is evaluated just once instead of twice.
>> 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.
Augmented *ASSIGNMENT* is a type of assignment.
The dis module can be used to see what CPython does.
>>> from dis import dis
>>> def f():
foo.bar += baz
>>> dis(f)
2 0 LOAD_GLOBAL 0 (foo)
3 DUP_TOP
4 LOAD_ATTR 1 (bar)
7 LOAD_GLOBAL 2 (baz)
10 INPLACE_ADD
11 ROT_TWO
12 STORE_ATTR 1 (bar)
...
This amounts to what Roy said, with x and y being temporary entries on
the stack.
Terry Jan Reedy
More information about the Python-list
mailing list