Python augmenting multiple variables inline

You cannot use an augmented assignment statement on multiple targets, no.

Quoting the augmented assignment documentation:

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.

Emphasis mine.

In-place augmented assignment is translated from target -= expression to target = target.__isub__(expression) (with corresponding __i...__ hooks for each operator) and translating that operation to multiple targets is not supported.

Under the hood, augmented assignment is a specialisation of the binary operators (+, *, -, etc), not of assignment. Because the implementation is based on those operators and binary operators only ever have two operands, multiple targets were never included in the original implementation proposal.

You’ll have to simply apply the assignments separately:

x -= 1
y -= 2

or, if you really, really wanted to get convoluted, use the operator module and zip() to apply operator.isub to the combinations (via itertools.starmap(), then use tuple assignment:

from operator import sub
from itertools import starmap

x, y = starmap(operator.isub, zip((x, y), (1, 2)))

where isub will ensure that the right hook is called allowing for in-place subtraction for mutable types that support it.

or, if you are manipulating types that don’t support in-place manipulation, using a generator expression suffices:

x, y = (val - delta for val, delta in zip((x, y), (1, 2)))

Leave a Comment