Sandro Dentella wrote: > I'd like to understand why += operator raises an error while .append() > does not. My wild guess is the parses treats them differently but I > cannot understand why this depends on scope of the variables (global > or class variables): > > > a = [0] > > class foo(object): > > def __init__(self): > print "a: ", a > # += does not work if 'a' is global > #a += [1] > a.append(2) > print "a= ", a >
Any assignment to a variable within a function means that the name to which you are assigning is regarded as a local variable (unless you use the 'global' statement to override that). += is a form of assignment, calling the append method is not an assignment. The solution here is simply to use 'global a' to tell the compiler that you meant to assign the the global variable rather than creating a new local variable. -- http://mail.python.org/mailman/listinfo/python-list