Skip to content

Commit f067db4

Browse files
authored
Fix OR pattern structural matching exhaustiveness (#18119)
Fixes #18108 This PR fixes the issue of missing value comparisons in a `MatchStmt` due to `OrPattern` incorrectly narrowing down the type of the subject.
1 parent 54a2c6d commit f067db4

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

mypy/checkpattern.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,8 @@ def visit_or_pattern(self, o: OrPattern) -> PatternType:
158158
for pattern in o.patterns:
159159
pattern_type = self.accept(pattern, current_type)
160160
pattern_types.append(pattern_type)
161-
current_type = pattern_type.rest_type
161+
if not is_uninhabited(pattern_type.type):
162+
current_type = pattern_type.rest_type
162163

163164
#
164165
# Collect the final type

test-data/unit/check-python310.test

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1721,6 +1721,22 @@ def f(x: int | str) -> int:
17211721
case str() as s:
17221722
return 1
17231723

1724+
[case testMatchOrPatternExhaustiveness]
1725+
from typing import NoReturn, Literal
1726+
def assert_never(x: NoReturn) -> None: ...
1727+
1728+
Color = Literal["blue", "green", "red"]
1729+
c: Color
1730+
1731+
match c:
1732+
case "blue":
1733+
reveal_type(c) # N: Revealed type is "Literal['blue']"
1734+
case "green" | "notColor":
1735+
reveal_type(c) # N: Revealed type is "Literal['green']"
1736+
case _:
1737+
assert_never(c) # E: Argument 1 to "assert_never" has incompatible type "Literal['red']"; expected "Never"
1738+
[typing fixtures/typing-typeddict.pyi]
1739+
17241740
[case testMatchAsPatternIntersection-skip]
17251741
class A: pass
17261742
class B: pass

0 commit comments

Comments
 (0)