Skip to content

Commit

Permalink
Fix OR pattern structural matching exhaustiveness (#18119)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
shenyih0ng authored Nov 11, 2024
1 parent 54a2c6d commit f067db4
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
3 changes: 2 additions & 1 deletion mypy/checkpattern.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,8 @@ def visit_or_pattern(self, o: OrPattern) -> PatternType:
for pattern in o.patterns:
pattern_type = self.accept(pattern, current_type)
pattern_types.append(pattern_type)
current_type = pattern_type.rest_type
if not is_uninhabited(pattern_type.type):
current_type = pattern_type.rest_type

#
# Collect the final type
Expand Down
16 changes: 16 additions & 0 deletions test-data/unit/check-python310.test
Original file line number Diff line number Diff line change
Expand Up @@ -1721,6 +1721,22 @@ def f(x: int | str) -> int:
case str() as s:
return 1

[case testMatchOrPatternExhaustiveness]
from typing import NoReturn, Literal
def assert_never(x: NoReturn) -> None: ...

Color = Literal["blue", "green", "red"]
c: Color

match c:
case "blue":
reveal_type(c) # N: Revealed type is "Literal['blue']"
case "green" | "notColor":
reveal_type(c) # N: Revealed type is "Literal['green']"
case _:
assert_never(c) # E: Argument 1 to "assert_never" has incompatible type "Literal['red']"; expected "Never"
[typing fixtures/typing-typeddict.pyi]

[case testMatchAsPatternIntersection-skip]
class A: pass
class B: pass
Expand Down

0 comments on commit f067db4

Please sign in to comment.