Skip to content

Commit 2b1f15c

Browse files
committed
Fix narrowing with chained comparison
Fixes #21149
1 parent ef7e8a6 commit 2b1f15c

2 files changed

Lines changed: 16 additions & 2 deletions

File tree

mypy/checker.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6674,8 +6674,8 @@ def comparison_type_narrowing_helper(self, node: ComparisonExpr) -> tuple[TypeMa
66746674
# If we have found non-trivial restrictions from the regular comparisons,
66756675
# then return soon. Otherwise try to infer restrictions involving `len(x)`.
66766676
# TODO: support regular and len() narrowing in the same chain.
6677-
if any(m != ({}, {}) for m in partial_type_maps):
6678-
return reduce_conditional_maps(partial_type_maps)
6677+
if any(len(m[0]) or len(m[1]) for m in partial_type_maps):
6678+
return reduce_conditional_maps(partial_type_maps, use_meet=True)
66796679
else:
66806680
# Use meet for `and` maps to get correct results for chained checks
66816681
# like `if 1 < len(x) < 4: ...`

test-data/unit/check-narrowing.test

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3264,6 +3264,20 @@ def bad_but_should_pass(has_key: bool, key: bool, s: tuple[bool, ...]) -> None:
32643264
reveal_type(key) # N: Revealed type is "builtins.bool"
32653265
[builtins fixtures/primitives.pyi]
32663266

3267+
[case testNarrowChainedComparisonMeet]
3268+
# flags: --strict-equality --warn-unreachable
3269+
from __future__ import annotations
3270+
3271+
def f1(a: str | None, b: str | None) -> None:
3272+
if None is not a == b:
3273+
reveal_type(a) # N: Revealed type is "builtins.str"
3274+
reveal_type(b) # N: Revealed type is "builtins.str | None"
3275+
3276+
if (None is not a) and (a == b):
3277+
reveal_type(a) # N: Revealed type is "builtins.str"
3278+
reveal_type(b) # N: Revealed type is "builtins.str"
3279+
[builtins fixtures/primitives.pyi]
3280+
32673281
[case testNarrowTypeObject]
32683282
# flags: --strict-equality --warn-unreachable
32693283
from typing import Any

0 commit comments

Comments
 (0)