0

In the examples below, x is assigned using the walrus operator and is then printed.

mystring = "hello, world"


#if 1
if x := mystring == "hello, world":
    print(x)

#if 2
if x := (mystring == "hello, world"):
    print(x)

#if 3
if (x := mystring) == "hello, world":
    print(x)

#if 4
if "hello, world" in (x := mystring):
    print(x)

The output:

True
True
hello, world
hello, world

I believe that I understand how each of these if statements works:

  1. #if 1 and #if 2 are the same thing where the string comparison == returns True, and that value is reassigned to x.

  2. #if 3 assigns mystring as x before checking the truth of this equal to "hello, world".

  3. #if 4assigns mystring as x then checks if "hello, world" is in this string.

So what about this final #if 5 is ambiguous to Python such that it gives a Syntax Error?

#if 5
if "hello, world" in x := mystring:
    print(x)
SyntaxError: cannot use assignment expressions with comparison

Is this related to PEP 572 Exceptional Cases:

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

there is no syntactic position where both are valid.

In reality I am looping through the pathlib Path.iterdir() generator object that yields strings with .stem. This does not change the result:

for file in folder.iterdir():
    x := file.stem == "mystring":
        print(x)
1
  • The in operator has higher priority than the := operator. What do you expect to happen to if ('hello world' in x) := mystring? Commented Oct 2, 2022 at 11:52

1 Answer 1

2

in and other comparison operators have a higher precedence than :=. So when you write

if "hello, world" in x := mystring:

it means:

if ("hello, world" in x) := mystring:

which is invalid as it tries to assign to "hello, world" in x. To get it you work you need to use parentheses:

if "hello, world" in (x := mystring):
Sign up to request clarification or add additional context in comments.

1 Comment

Obvious now you say it that statements including operators with words like 'in' are in a precedence hierarchy. I'd just assumed symbols over everything first?

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.