|augmented_assignment_stmt||::=||target augop expression_list|
|augop||::=||"+=" | "-=" | "*=" | "/=" | "%=" | "**="|
(See section 5.3 for the syntax definitions for the last three symbols.)
An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns the result to the original target. The target is only evaluated once.
An augmented assignment expression like
x += 1 can be rewritten as
x = x + 1 to achieve a similar, but not exactly equal effect. In the
x is only evaluated once. Also, when possible, the
actual operation is performed in-place, meaning that rather than
creating a new object and assigning that to the target, the old object is
With the exception of assigning to tuples and multiple targets in a single statement, the assignment done by augmented assignment statements is handled the same way as normal assignments. Similarly, with the exception of the possible in-place behavior, the binary operation performed by augmented assignment is the same as the normal binary operations.
For targets which are attribute references, the initial value is retrieved with a getattr() and the result is assigned with a setattr(). Notice that the two methods do not necessarily refer to the same variable. When getattr() refers to a class variable, setattr() still writes to an instance variable. For example:
class A: x = 3 # class variable a = A() a.x += 1 # writes a.x as 4 leaving A.x as 3
See About this document... for information on suggesting changes.