Walrus operator in Python interpreter

988 Views Asked by At

When I use the walrus operator as below in the Python(3.9.6) interpreter,

>>> walrus:=True

I get a syntax error:

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

How is this different from the following?

>>> print(walrus := True)
1

There are 1 best solutions below

0
On BEST ANSWER

It's different because the Python core developers were very ambivalent about violating the Zen of Python guideline "There should be one-- and preferably only one --obvious way to do it", and chose to make it inconvenient to replace most uses of plain = with := without adding additional parentheses to the expression.

Rather than allowing := to replace = in all contexts, they specifically prohibited unparenthesized top-level use of the walrus:

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

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.

In many cases where := is prohibited, you can make it valid by adding otherwise unnecessary parentheses around the expression, so:

(walrus:=True)

works just fine, but it's enough of a pain that the assumption is that most people will stick to the simpler and more Pythonic:

walrus = True

in that scenario.