Augmented Assignment in Python (PER)

David Beazley beazley at cs.uchicago.edu
Wed Jul 18 03:11:51 CEST 2001


James_Althoff at i2.com writes:
 > 
 > David,
 > 
 > There was a fairly lengthy and animated exchange (which you might have
 > seen) recently on python-list at python.org concerning augmented assigment.
 > Unless I'm very mixed up, it appears that your book presents augmented
 > assignment according to the way that many folks seem to think it works,
 > which according to Thomas -- and verified easily with Python test cases --
 > is, in fact, *not* the way it actually works.
 > 
 > Thought you might want to know (you might already be very aware of this).
 > 
 > Jim
 > 
 > 
 > Thomas Wouters wrote:
 > <snip>
 > >No, that's the *whole intent* of the thing. If x += y was supposed to be
 > >*exactly* the same as x = x + y, it would have been spelled as 'x = x +
 > y'.
 > >It isn't, and it's not. It's not supposed to be syntactic sugar for normal
 > >addition, it's supposed to be syntactic sugar for a method call.
 > >
 > >Thomas Wouters <thomas at xs4all.net>
 > 
 > >From "Python Essential Reference", Second Edition, David M. Beazley
 > pages 48 - 49:
 > 
 > "
 > Python provides the following set of augmented assignment operators:
 > ---------    -----------
 > Operation    Description
 > ---------    -----------
 > x += y       x = x + y
 > 
 > <snip>
 > 
 > Augmented assignment doesn't violate mutability or perform in-place
 > modification of objects. Therefore, writing x += y creates an entirely new
 > object x with the value x + y.
 > "

Well, I seem to have gotten in on this fray rather late.   However, to 
clarify the contents of the Python Essential Reference, the book does
discuss the fact that the augmented assignment operators are mapped to
a certain set of special methods such as __iadd__() and that user
defined classes/types can override these methods (p. 37-38,
p.49).  Admittedly, this presentation is rather terse--keeping in
style with other parts of the book.  

I think the above sentence would make a lot more sense if it was
worded as follows:

"For the built-in types, augmented assignment doesn't violate
mutability or perform in-place modification of objects. Therefore,
writing x+=y creates an entirely new object x with the value x + y.
User defined types and classes may choose to implement different
behavior by redefining special methods such as __iadd__(), __isub__(), 
and so forth."

Note: I still stand by the statement for built-in types.  I looked through
the Python sources when writing the book and couldn't find any use of
augmented assignment for built-in types.  I am not aware of any
counter-example where x += y is not equal to x = x + y for the standard
built-in types (if there is such an example, please enlighten me!).

I'll see if I can add some clarification on this issue in the second
printing.

Cheers,

Dave














More information about the Python-list mailing list