4

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.

WoJ
  • 19,312
  • 30
  • 122
  • 230

1 Answers1

4

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()):
    ...
khelwood
  • 46,621
  • 12
  • 59
  • 83
  • It's kinda odd/funny because that `not` operator actually doesn't end up being done as one there, at least not in CPython. Instead the `if not` is rather treated like an `unless` statement, using `POP_JUMP_IF_TRUE` instead of an `if`'s `POP_JUMP_IF_FALSE`. [Demo](https://tio.run/##LYsxCsAgDAB3X5ExWbp0KULfUgQbmkENmsXXpxZ6cNNxOu1pdT@0u0vR1g2yjBDyzcBIMcBCGGozwATxhJHmdRe1ifTnD@1SDWmNMrYlMrm/). – superb rain Feb 20 '21 at 08:17