[Python-ideas] Why does += trigger UnboundLocalError?

Ethan Furman ethan at stoneleaf.us
Wed Jun 1 19:51:30 CEST 2011


Bruce Leban wrote:
> 
> 
> On Wed, Jun 1, 2011 at 9:56 AM, Ethan Furman wrote:
> 
> 
>     Several times in that thread it was stated that
> 
>     --> a += 1
> 
>     is a shortcut for
> 
>     --> a.__iadd__(1)
> 
>     It seems to me that this is an implementation detail, and that the
>     actual "longcut" is
> 
>     --> a = a + 1
> 
>     ...
> 
>     ~Ethan~
> 
>  
> a += 1 is not a shortcut for a.__iadd__(1). It's a shortcut for a = 
> a.__iadd(1). Otherwise this wouldn't work:

Right -- typo on my part, sorry.


> Note the difference between these two is one opcode:
> 
>  >>> def f(x,y):
> x += y
>  >>> dis.dis(f)
>   2           0 LOAD_FAST                0 (x)
>               3 LOAD_FAST                1 (y)
>               6 *INPLACE_ADD*         
>               7 STORE_FAST               0 (x)
>              10 LOAD_CONST               0 (None)
>              13 RETURN_VALUE        
>  >>> def g(x,y):
> x = x + y
> 
>  >>> dis.dis(g)
>   2           0 LOAD_FAST                0 (x)
>               3 LOAD_FAST                1 (y)
>               6 *BINARY_ADD*          
>               7 STORE_FAST               0 (x)
>              10 LOAD_CONST               0 (None)
>              13 RETURN_VALUE        

Note also that INPLACE_ADD will call the the BINARY_ADD method if no 
__iadd__ method exists.

~Ethan~



More information about the Python-ideas mailing list