2

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)
Chris_Rands
  • 30,797
  • 12
  • 66
  • 100
Richard Neumann
  • 1,880
  • 1
  • 16
  • 37
  • 2
    Well `as` is a keyword that is already part of the language, e.g. `import itertools as it` or `with open(file) as f:` etc. – Chris_Rands Sep 20 '19 at 14:01
  • 1
    Exactly my point. It already has two uses, like `from`. Why not add a third? – Richard Neumann Sep 20 '19 at 14:02
  • 3
    I presume that the parsing is easier for the new symbol than overloading the `as` operator (maybe ambiguities?). Also makes it easier for users to differentiate uses than having one symbol /operator for many different cases – Nikos M. Sep 20 '19 at 14:02
  • 3
    https://www.python.org/dev/peps/pep-0572/#alternative-spellings – Chris_Rands Sep 20 '19 at 14:05
  • @Chris_Rands Thank you, this basically answered it. I must have skipped that while reading the PEP. – Richard Neumann Sep 20 '19 at 14:06

1 Answers1

5

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

Chris_Rands
  • 30,797
  • 12
  • 66
  • 100