Augmented assignment (was Re: Something in the function tutorial confused me.)

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Sat Aug 11 19:21:28 CEST 2007


Aahz schreef:
>>>> def foo(bar): bar[0] += ['zap']
> ... 
>>>> import dis
>>>> dis.dis(foo)
>   1           0 LOAD_FAST                0 (bar)
>               3 LOAD_CONST               1 (0)
>               6 DUP_TOPX                 2
>               9 BINARY_SUBSCR       
>              10 LOAD_CONST               2 ('zap')
>              13 BUILD_LIST               1
>              16 INPLACE_ADD         
>              17 ROT_THREE           
>              18 STORE_SUBSCR        
>              19 LOAD_CONST               0 (None)
>              22 RETURN_VALUE        
> 
> Notice the critical sequence: BINARY_SUBSCR, INPLACE_ADD, STORE_SUBSCR.
> It has to work that way to allow this:
> 
>>>> l = [7]
>>>> l[0] += 1
>>>> l
> [8]
> 
> There's simply no way to get augmented assignment to work correctly with
> both lists and tuples when you allow both mutable and immutable elements.
> Someone will always get surprised, and overall with strings and numbers
> being the canonical list elements, I think making augmented assignment
> work correctly with lists and immutables was the best decision.

Thank you, I get it now. With that disassembled code in mind I had 
another look at the relevant section in the Language Reference; now I 
have a much better understanding of what's really happening.

I used to interpret the target in 'The target is only evaluated once' 
more like an L-value in C/C++. That's not correct, of course, but I 
didn't understand exactly how wrong it was until now.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven



More information about the Python-list mailing list