Compound Assignment Operators ( +=, *=, etc...)

Timothy R Evans tre17 at pc142.cosc.canterbury.ac.nz
Sun Aug 15 21:20:50 EDT 1999


Drew McDowell <drew.mcdowell at msfc.nasa.gov> writes:

> I looked in the FAQ and couldn't find anything on the Compound
> Assignment Operators.
> (+=, *=, -=, etc..)
> Why dosen't Python support them?  Is there a easy way to add them?
> 
> -Drew McDowell

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
global variables.

>>> def foo():
...    x += 2
...    return x
>>> x = 42
>>> foo()
44
>>> 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.

Confused yet, well here's a second reason.

>>> x = [1,2,3,4]
>>> y = x
>>> x += [5,6]
>>> x
[1,2,3,4,5,6]
>>> y
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.

--
Tim Evans






More information about the Python-list mailing list