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

Jacob Holm jh at improva.dk
Wed Jun 1 11:09:06 CEST 2011

I think you missed this statement, even though you quoted it.

On 2011-06-01 10:51, Paul Moore wrote:
> On 1 June 2011 09:26, Carl M. Johnson <cmjohnson.mailinglist at gmail.com> wrote:
>> We
>> all agree that if there's an x= somewhere in the function body, then we have
>> to treat the variable as a local. 

This means that your example:

> x = 1
> def f():
>     # The next statement uses the global x
>     x += 1
>     x = 2
>     # From here, you have a local x

Would behave exactly as it does today under the proposed new semantics.
 Specifically, the "x = 2" statement (and the lack of a nonlocal
statement) forces x to be local throughout the function, and the "x +=
1" statement then tries to read the local "x" and fails.

> That fundamentally changes the language semantics.

I don't think it does.  It only makes a difference for functions that
contains an augmented assignment to a name without also containing a
regular assignment to that name.  This case will change from being an
error to doing something well-defined and useful.

FWIW, I'm +1 on the idea.

Best regards

 - Jacob

More information about the Python-ideas mailing list