Search code examples
pythonpython-3.xlanguage-designpython-3.8python-assignment-expression

Understanding the reason for the new python := operator


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)

Solution

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