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

Ethan Furman ethan at stoneleaf.us
Wed Jun 1 13:24:30 CEST 2011


Carl M. Johnson wrote:
> On Tue, May 31, 2011 at 7:48 PM, Georg Brandl wrote:
>> 
>> Because x += y is equivalent to
>> 
>> x = x.__iadd__(y)
>> 
>> and therefore an assignment is going on here.  Therefore, it's only
>> logical to treat it as such when determining scopes.
> 
> But the difference is that you can only use += if the LHS name already 
> exists and is defined. So, it couldn't possibly be referring to a local 
> name if it's the only assignment-like statement within a function body. 
> How could it refer to a local if it has to refer to something that 
> already exists?

Two problems.  Firstly, what error should be raised here?

--> def accum():
...     x = 0
...     def inner():
...         x1 += 1
...         return x
...     return inner

Secondly, the += operator may or may not be a mutating operator 
depending on the object it's used on:  if the object does not have a 
__iadd__ method, it's not mutating; even if it does have an __iadd__ 
method, it may not be mutating -- it's up to the object to decide.

--> class ex_int(int):
...   def __iadd__(self, other):
...     return self + other
...
--> x = ex_int(7)
--> x.__iadd__(3)
10
--> x
7
--> x = [1, 2, 3]
--> x.__iadd__([4])
[1, 2, 3, 4]
--> x
[1, 2, 3, 4]

-1 on changing the semantics.

~Ethan~



More information about the Python-ideas mailing list