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

Steven D'Aprano steve at pearwood.info
Thu Jun 2 01:21:12 CEST 2011

Carl M. Johnson wrote:

> Agreed, sure, we have to treat the LHS of = as
> a local. But += is fundamentally different. 

No it's not. It is fundamentally the same. Augmented assignment in 
Python *is* assignment, equivalent to x = x.__iadd__(other). That alone 
should be enough to kill this proposal stone dead.

+= is not, except by accident, an in-place addition operator. It is 
always a re-binding. (Mutable objects are free to mutate in place, if 
they choose, but the re-binding still takes place.)

> You cannot have a += statement
> unless somewhere out there there is a matching = statement. It cannot exist
> independently. It never works on its own. 

Neither does *any* attempt to access an unbound local. Python doesn't, 
and shouldn't, try to guess what you actually intended so as to make it 
work. If you want x to refer to a nonlocal, or a global, declare it as such.

print x; x = 1 will fail unless there is an earlier x = something.

x = x+1 will fail unless there is an earlier x = something.

x += 1 will fail unless there is an earlier x = something.

Why single out x += 1 for changed semantics to the rule that any 
assignment makes x a local? What if you don't have a non-local x, should 
Python guess that you wanted a global?

Currently, the rule is simple: any assignment tells the compiler to 
treat x as local. If you want nonlocal or global, you have to declare it 
as such. Nice and simple. What actual real-world problem are you trying 
to solve that you want to change this behaviour?

-1 on this change.


More information about the Python-ideas mailing list