Search code examples
pythonterminalwalrus-operator

Why isn't the walrus operation a valid statement?


I was doing some python in a terminal, at a point I wrote x := 1 and it showed a Syntax Error.

>>> x := 1
  File "<stdin>", line 1   
    x := 1
      ^
SyntaxError: invalid syntax

I know that the walrus operator is an expression, but other expressions work perfectly.

>>> 5 + 3 - 1
7 

Even the walrus operation work inside parentheses.

>>> (x := 1)
1

So my question is, Why are every other expression valid as a statement, but walrus isn't?


Solution

  • From PEP 572, "Exceptional cases" (emphasis mine):

    Unparenthesized assignment expressions are prohibited at the top level of an expression statement. Example:

    y := f(x)  # INVALID
    (y := f(x))  # Valid, though not recommended
    

    This rule is included to simplify the choice for the user between an assignment statement and an assignment expression -- there is no syntactic position where both are valid.

    It was simple to exclude bare assignment expressions in the grammar. It would have been much more complicated to ban only some parenthesized expressions (namely, those that contain assignment expressions) while still allowing others, which is why (y := f(x)) is valid.