了解新 python := 运算符的原因

Understanding the reason for the new python := operator

这是一个元编程问题:我想了解为什么 python 开发人员使用新的 := 引入了另一个运算符。我知道这是干什么的。但是,我想知道为什么开发人员选择了一个新符号而不是重新使用例如as 运算符。

即为什么写

更可取
while (command := input("> ")) != "quit":
    print("You entered:", command)

而不是

while input("> ") as command != "quit":
    print("You entered:", command)

这在 PEP 572

中得到了回答

Alternative spellings

Broadly the same semantics as the current proposal, but spelled differently.

EXPR as NAME:

stuff = [[f(x) as y, x/y] for x in range(5)]

Since EXPR as NAME already has meaning in import, except and with statements (with different semantics), this would create unnecessary confusion or require special-casing (e.g. to forbid assignment within the headers of these statements).

(Note that with EXPR as VAR does not simply assign the value of EXPR to VAR -- it calls EXPR.__enter__() and assigns the result of that to VAR.)

Additional reasons to prefer := over this spelling include:

In if f(x) as y the assignment target doesn't jump out at you -- it just reads like if f x blah blah and it is too similar visually to if f(x) and y.

In all other situations where an as clause is allowed, even readers with intermediary skills are led to anticipate that clause (however optional) by the keyword that starts the line, and the grammar ties that keyword closely to the as clause:

import foo as bar

except Exc as var

with ctxmgr() as var

To the contrary, the assignment expression does not belong to the if or while that starts the line, and we intentionally allow assignment expressions in other contexts as well.

The parallel cadence between

NAME = EXPR

if NAME := EXPR

reinforces the visual recognition of assignment expressions.