Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

operators - Python augmenting multiple variables inline

Why does this work

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

But augmenting results in syntax errors..

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

Is there a different way, I was expecting:

>> x, y -= (1, 2)
>> print x, y
0 0
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...