2

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)
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
BlueGene
  • 1,071
  • 1
  • 20
  • 30
  • 4
    Assignment expressions must be enclosed in parens. They work inside function calls like this, though, similar to how bare generator expressions must be enclosed but can be passed in a function call, e.g. `sum(x for x in some_iterable)`. – ddejohn Sep 15 '21 at 15:46
  • 1
    This is just how it's degined. See: https://www.python.org/dev/peps/pep-0572/#exceptional-cases – gen_Eric Sep 15 '21 at 15:47
  • I meant designed* – gen_Eric Sep 15 '21 at 15:54

1 Answers1

3

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.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271