Compound Assignment Operators ( +=, *=, etc...)
tchrist at mox.perl.com
Thu Aug 19 05:17:07 CEST 1999
[courtesy cc of this posting mailed to cited author]
Timothy R Evans <tre17 at pc142.cosc.canterbury.ac.nz> writes:
:One reason that these constructs could cause problems is due to
:namespaces. Assuming that x += y is expanded to x = x + y, consider
:the following code while remembering how python treats namespaces and
:>>> def foo():
:... x += 2
:... return x
:>>> x = 42
:I don't think this is what you want to happen, but it is what python
:would do. Inside foo(), the global variable x is read, then a local
:variable x is created (there is no `global x' in the function). So in
:this case x += 2 does not add 2 to x, it creates a new local variable
:that is 2 greater than the global variable of the same name.
That's not the way I dimly understand it. You can't from a local
scope even try to do a
x = x + 2
on a global, unless you declare x to be global. Anything else is illegal,
because you'd end up talking about a global and a local at the same
time. Consider if your function were written:
x = x + 2
That's not legal even now. You need the global.
:Confused yet, well here's a second reason.
:>>> x = [1,2,3,4]
:>>> y = x
:>>> x += [5,6]
:what should this be?
:you would expect x += y on lists to actually extend the list, or do
:you want it to be x = x + y, which could be really slow on big lists,
:while hiding the fact that it is copying the list.
I think you've pointed out a real issue here, but it's not the "big lists
are slow one". That's just something the compiler should just optimize.
The real issue is the aliasing issue. If you write:
x = [1,2,3,4]
y = x
Then you are expecting x and y to refer to the same object. If you use
x = x + [5,6]
then you've orphaned y, which remains as it was due to the
semantics of "+" providing a new result list.
Is this bad? I don't know for sure. Sometimes it seems to make sense.
Certainly if you write
x = 4
y = x
x = x + 2
you don't expect y to track the changes to x and also be 6.
I don't really see any reason for
var += expr
to be defined in any terms other than
var = var + expr
However, I do see ample opportunity for optimization, some of which
might be easier given += then it would be if written out long hand.
"The purpose of most computer languages is to lengthen your resume by
a word and a comma." --Larry Wall
More information about the Python-list