This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Inconsistent behaviour when using walrus operator with 'and'/'or'
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.10, Python 3.9, Python 3.8
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: FuturisticGoo, eric.smith
Priority: normal Keywords:

Created on 2021-01-28 11:58 by FuturisticGoo, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg385853 - (view) Author: Futuristic Goo (FuturisticGoo) Date: 2021-01-28 11:58
Using the walrus operator (:=) alongside 'and'/'or' shows inconsistent behaviour which changes with the order of given conditions. 

For example:
if(False and (x := 0)<1):
    print("Yes")
else:
    print(x)

Gives the error that 'NameError: name 'x' is not defined'
Whereas if the walrus operator is used first, like:
if((x := 0)>1 and False):
    print("Yes")
else:
    print(x)

Prints the value 0 without any error. This behaviour is the same when using 'or'. For example:

if(True or (y:=0)<1):
    print(y)
else:
    print("No")

Gives the same error but this:
if((y:=0)<1 or True):
    print(y)
else:
    print("No")

Prints the value 0.
I am guessing that this is because 'and' doesn't check the second operand if the first operand is False, also 'if' doesn't check the second operand if the first operand is True. I don't know if this is an intended behaviour.

Thanks
msg385858 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2021-01-28 13:30
I think this is pretty clearly the intended semantics. In your first example, what do you propose "print(x)" would produce? Consider:

if False and (x:=input()) != '':
  pass
else:
  print(x)

We cannot change the semantics to now call input(), or any function with side effects, just to do the assignment to x.
msg385860 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2021-01-28 13:36
I'm going to close this. The short circuit evaluation of and/or expressions is already documented, and this behavior follows directly from that.
History
Date User Action Args
2022-04-11 14:59:40adminsetgithub: 87221
2021-01-28 13:36:04eric.smithsetstatus: open -> closed
resolution: not a bug
messages: + msg385860

stage: resolved
2021-01-28 13:30:40eric.smithsetnosy: + eric.smith
messages: + msg385858
2021-01-28 11:58:35FuturisticGoocreate