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)
3
  • 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). Commented Sep 15, 2021 at 15:46
  • 1
    This is just how it's degined. See: python.org/dev/peps/pep-0572/#exceptional-cases Commented Sep 15, 2021 at 15:47
  • I meant designed* Commented Sep 15, 2021 at 15:54

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What is "the top level of an expression statement"?
@AntoniosSarikas: An expression statement is an expression used as a statement. Top-level means "it's the outermost expression (in the expression statement). The example is demonstrating this; without the parentheses, the walrus is at the top level, with the parentheses, it's not. Sorry I can't give a more rigorous definition off-the-cuff, but this is easier as "you know it when you see it".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.