Why does "if not a := say_empty()" raise a SyntaxError?
Asked Answered
S

1

14

PEP 572 introduces the assignement operator ("walrus operator").

The following code works, and outputs empty

def say_empty():
    return ''

if a := say_empty():
    print("not empty")
else:
    print("empty")

I tried to negate the condition:

def say_empty():
    return ''

if not a := say_empty():
    print("empty")
else:
    print("not empty")

This raises a SyntaxError

    if not a := say_empty():
       ^
SyntaxError: cannot use assignment expressions with operator

The given error is clear, I am however wondering why this limitation was put in place.

PEP 572 explains why using the assignment in iterations is problematic (and raises SyntaxError), but I did not find anything about boolean ones.

Subordinate answered 20/2, 2021 at 7:47 Comment(0)
S
25

Operator precedence indicates that := has a lower precedence than not. So not a := is read as trying to assign to not a, hence the syntax error.

You can use parentheses to clarify the meaning:

if not (a := say_empty()):
    ...
Spotless answered 20/2, 2021 at 7:54 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.