It seems this question only answered for Java but I would like to know how it works in Python. So are these the same?
a += b / 2
and
a += (b / 2)
Yes, those are the same. Python's augmented assignment is not an expression, it is a statement, and doesn't play in expression precedence rules. +=
is not an operator, and instead it's part of the augmented assignment statement syntax.
So everything to the right of the +=
is an expression, but +=
itself is not, so the assignment will always be handled last.
And because (augmented) assignment is not an expression, it can't produce a value to use in a surrounding expression either. There is no (a += b) / 2
, that'd be a syntax error, and certainly no if (a += b / 2):
or other such shenanigans.
See the reference documentation on Augmented assignment statements, which states the grammar is:
augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression) augtarget ::= identifier | attributeref | subscription | slicing augop ::= "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**=" | ">>=" | "<<=" | "&=" | "^=" | "|="
So the augop
is part of the statement syntax, and only the part following is an expression (specifically, either a expression_list
or yield_expression
grammar rule).
Furthermore, the explanation shows:
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.
So the augtarget
part is handled first, the expression list (or yield expression) is handled second, and then the augmented assignment applies the operator and assigns back the result.
Furthermore, the expressions reference documentation does include a precedence table, but that table doesn't include assignments (augmented or otherwise), simply because assignments are not expressions but statements.