Python padding multiple inline variables

Why does this work

>> x, y = (1, 2)
>> print x, y
1 2

      

But results increase on syntax errors.

>> x, y -= (1, 2)
SyntaxError: illegal expression for augmented assignment

      

Is there any other way I was expecting:

>> x, y -= (1, 2)
>> print x, y
0 0

      

+16


source to share


2 answers


You cannot use the extended assignment operator for multiple purposes, no.

Quoting the updated assignment documentation :

With the exception of tuple assignments and multiple targets in a single statement , assignments made by extended assignment operators are treated in the same way as regular assignments. Likewise, except for possible in-place behavior, the binary operation performed by augmented assignment is the same as normal binary operations.

Emphasis on mine.

Extended in-place assignment is translated from target -= expression

to target = target.__isub__(expression)

(with appropriate hooks __i...__

for each operator) and cross-targeting of this operation is not supported.

Under the hood, extended assignment - a specialization binary operators ( +

, *

, -

etc.), not the destination. Since the implementation is based on these operators, and binary operators only have two operands, multiple targets were never included in the original sentence.

You just need to apply the assignments separately:



x -= 1
y -= 2

      

or, if you really want to get confused, use module operator

and zip()

to apply operator.isub

to 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 in-place subtraction for mutable types that support it.

or, if you are manipulating types that do not support in-place manipulation, a generator expression is sufficient:

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

      

+15


source


This x, y = (1, 2)

is the purpose of the sequence. It assumes that the right side is an iterable and the left side consists of the same number of variables as the left side is iterated.



This one x, y -= (1, 2)

tries to call the method __isub__

on the left operand (s). The nature of the assignment in place ("extended") is that it must take a variable on the left side, the value of which is received by the operator call, and then the variable receives the result of that call. Python does not allow in-place assignment to be distributed across multiple targets.

+2


source







All Articles