classification
Title: Exception handling on boolean comparisons
Type: behavior Stage: resolved
Components: Versions: Python 3.8
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: CanisUrsa, steven.daprano
Priority: normal Keywords:

Created on 2020-11-17 21:37 by CanisUrsa, last changed 2020-11-17 21:53 by steven.daprano. This issue is now closed.

Messages (2)
msg381289 - (view) Author: Christopher Contaxis (CanisUrsa) Date: 2020-11-17 21:37
Python 3.8.6 will not produce an exception when comparing values in an and/or statement that normally produces an exception standalone.

val = 0
low = 1
high = "2"

The following makes sense:

val >= low : False
val <= high : Exception, cant compare int and str
val <= high and val >= low : Exception, cant compare int and str

The following doesn't make sense (doesn't produce an exception):

val >= low and val <= high : False
msg381291 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2020-11-17 21:53
This is not a bug, it is normal handling of `and` and `or` operators since Python 1.5 and possibly older.

The `and` and `or` operators are *short-cut* operators. This is intentional design, so we can write things like:

    if mylist and mylist[0] == value:

the `mylist[0] == value` expression is only evaluated if `mylist` is a truthy value.

This is all documented here:

https://docs.python.org/3/reference/expressions.html#boolean-operations
History
Date User Action Args
2020-11-17 21:53:25steven.dapranosetstatus: open -> closed

nosy: + steven.daprano
messages: + msg381291

resolution: not a bug
stage: resolved
2020-11-17 21:37:45CanisUrsacreate