Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 357
Was Avatar asked Nov 02 '25 05:11

Was


1 Answers

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.

like image 78
chepner Avatar answered Nov 03 '25 18:11

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!