lists: += vs. .append() & oddness with scope of variables

Terry Reedy tjreedy at udel.edu
Sun Mar 5 14:02:25 EST 2006


"Sandro Dentella" <sandro at e-den.it> wrote in message 
news:slrne0lk30.ek2.sandro at bluff.diade.it...
> I'd like to understand why += operator raises an error while .append() 
> does
> not.

Your mistake is thinking of '+=' as an operator.  In Python terms it is 
not, any more than '=' is.  In Python, neither 'a=b' nor 'a+=b' is an 
expression.  Both symbols are statement symbols that define assigment 
statements (augmented in the former case).  "a.append(b)" is an expression 
with side effects used as a statement.

> Traceback (most recent call last):
>  File "c1.py", line 26, in ?
>    x = foo()
>  File "c1.py", line 7, in __init__
>    print "a: ", a
> UnboundLocalError: local variable 'a' referenced before assignment

This is the clue that you did not get.  It tells you that the parser thinks 
'a' is local, which means you rebound the name 'a' *somewhere* in the 
function, even if not as obviously as a simple assignment "a = whatever". 
It turns out that augmented assignment statements are assignments 
statements ;-).

Terry Jan Reedy






More information about the Python-list mailing list