This is kind of a meta programming question: I'd like to understand why python developers introduced yet another operator with the new :=
. I know what it's for. I would, however, like to know, why the developers chose a new symbol instead of re-using e.g. the as
operator.
I.e. why was it deemed preferable to write
while (command := input("> ")) != "quit":
print("You entered:", command)
rather than
while input("> ") as command != "quit":
print("You entered:", command)
This is answered in 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 inimport
,except
andwith
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 ofEXPR
toVAR
-- it callsEXPR.__enter__()
and assigns the result of that toVAR
.)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 likeif f x blah blah
and it is too similar visually toif 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 theas
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
orwhile
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.