15

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

I tried to negate a 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

I am 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.

0

1 Answer 1

27

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()):
    ...
Sign up to request clarification or add additional context in comments.

Comments

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.