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

Ethan Furman ethan at stoneleaf.us
Wed Jun 1 18:56:47 CEST 2011

Nick Coghlan wrote:
> On Wed, Jun 1, 2011 at 2:52 PM, Carl M. Johnson
> <cmjohnson.mailinglist at gmail.com> wrote:
>> We all know that the following code won't work because of UnboundLocalError
>> and that to get around it, one needs to use nonlocal:
> There's no fundamental reason this couldn't change, but actually
> changing it simply isn't worth the hassle, so the status quo wins the
> stalemate.
> I elaborated further on this point when the topic came up last year:
> http://mail.python.org/pipermail/python-ideas/2010-June/007448.html

Maybe I get to learn something new about Python today.

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

Likewise, the shortcut of

--> some_list[func_with_side_effects()] += some_value

is the same as

--> index = func_with_side_effects()
--> some_list[index] = some_list[index] + some_value

Is my understanding correct?


More information about the Python-ideas mailing list