Skip to content

Commit ac4705a

Browse files
fix(rewrite): short-circuit chained comparisons (pytest-dev#14819)
Python evaluates a comparison chain lazily -- in `a < b < c`, c is never evaluated when a < b is false. visit_Compare walked the comparators in a loop and only combined the results with `and` afterwards, by which time everything had already run: assert 1 < 0 < 1 / 0 # ZeroDivisionError, not AssertionError Each link past the first now goes inside an `if` on the link before it, the same shape visit_BoolOp has used since #57 was fixed for and/or. The failure path builds a tuple of every link's result and every operand, so the temporaries belonging to links that never ran are set to None ahead of the chain rather than left unbound. None is falsey, which is also what _call_reprcompare wants: it stops at the first falsey result, and that is the link that actually failed. Closes the order-chained-compare-lazy group in the coverage matrix.
1 parent 382db6b commit ac4705a

3 files changed

Lines changed: 51 additions & 0 deletions

File tree

‎changelog/14822.bugfix.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Chained comparisons in an ``assert`` now short-circuit the way Python does: in ``assert a < b < c``, ``c`` is no longer evaluated when ``a < b`` is false. Previously ``assert 1 < 0 < 1 / 0`` raised ``ZeroDivisionError`` instead of ``AssertionError``, and a call in an unreached position ran anyway.

‎src/_pytest/assertion/rewrite.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1191,7 +1191,22 @@ def visit_Compare(self, comp: ast.Compare) -> tuple[ast.expr, str]:
11911191
expls: list[ast.expr] = []
11921192
syms: list[ast.expr] = []
11931193
results = [left_res]
1194+
# A chain short-circuits: ``a < b < c`` leaves c unevaluated when a < b
1195+
# is false. Everything past the first link therefore goes inside an
1196+
# ``if`` on the link before it, and the temporaries it would have
1197+
# produced are set to None up front -- the failure path builds a tuple
1198+
# of all of them, and the ones that never ran must still be readable.
1199+
# None is also falsey, so _call_reprcompare still stops at the link
1200+
# that actually failed.
1201+
body = self.statements
1202+
deferred_at = deferred_from = None
11941203
for i, op, next_operand in it:
1204+
if i:
1205+
if deferred_at is None:
1206+
deferred_at, deferred_from = len(body), len(self.variables)
1207+
inner: list[ast.stmt] = []
1208+
self.statements.append(ast.If(load_names[i - 1], inner, []))
1209+
self.statements = inner
11951210
next_res, next_expl = self.visit_operand(
11961211
next_operand, comp.comparators[i + 1 :]
11971212
)
@@ -1207,6 +1222,17 @@ def visit_Compare(self, comp: ast.Compare) -> tuple[ast.expr, str]:
12071222
res_expr = ast.copy_location(ast.Compare(left_res, [op], [next_res]), comp)
12081223
self.statements.append(ast.Assign([store_names[i]], res_expr))
12091224
left_res, left_expl = next_res, next_expl
1225+
self.statements = body
1226+
if deferred_at is not None:
1227+
assert deferred_from is not None
1228+
deferred = [*res_variables[1:], *self.variables[deferred_from:]]
1229+
body.insert(
1230+
deferred_at,
1231+
ast.Assign(
1232+
[ast.Name(name, ast.Store()) for name in deferred],
1233+
ast.Constant(None),
1234+
),
1235+
)
12101236
# Use pytest.assertion.util._reprcompare if that's available.
12111237
expl_call = self.helper(
12121238
"_call_reprcompare",

‎testing/test_assertrewrite_coverage.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1193,6 +1193,30 @@ def check():
11931193
return "passed", value
11941194
""")
11951195

1196+
def test_chained_compare_stops_at_the_first_false(self) -> None:
1197+
assert_evaluation_order("""
1198+
def check():
1199+
trace = []
1200+
def rec(label, value):
1201+
trace.append(label)
1202+
return value
1203+
try:
1204+
assert rec("a", 1) < rec("b", 0) < rec("c", 5)
1205+
except AssertionError:
1206+
return "raised", trace
1207+
return "passed", trace
1208+
""")
1209+
1210+
def test_chained_compare_unreached_operand_does_not_raise(self) -> None:
1211+
assert_evaluation_order("""
1212+
def check():
1213+
try:
1214+
assert 1 < 0 < 1 / 0
1215+
except AssertionError:
1216+
return "raised", None
1217+
return "passed", None
1218+
""")
1219+
11961220
def test_method_lookup_precedes_arguments(self) -> None:
11971221
"""Guard: the bound method is looked up before the arguments run."""
11981222
assert_evaluation_order("""

0 commit comments

Comments
 (0)