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)
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:In many cases where
:=
is prohibited, you can make it valid by adding otherwise unnecessary parentheses around the expression, so: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:
in that scenario.