From 5773f2ca945f079f030ce9e9cb17e94a48cb5da7 Mon Sep 17 00:00:00 2001 From: pei711 Date: Wed, 18 Nov 2026 11:48:23 +0000 Subject: [PATCH] Fix false unreachable errors in tuple union patterns --- mypy/checkpattern.py | 11 ++++++++++- test-data/unit/check-python310.test | 26 ++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/mypy/checkpattern.py b/mypy/checkpattern.py index 0e4786910e116..b03e5586d9728 100644 --- a/mypy/checkpattern.py +++ b/mypy/checkpattern.py @@ -264,7 +264,16 @@ def visit_sequence_pattern(self, o: SequencePattern) -> PatternType: star_expr = None for t in current_type.items: - match_type, rest_type, captures = self.accept(o, t) + # A diagnostic from one union alternative may not apply to the + # pattern as a whole. For example, in tuple[A, None] | tuple[B, int], + # `case A, None` matches the first alternative; checking the second + # alternative independently would incorrectly report `None` as + # unreachable against `int`. + watcher = self.msg.filter_errors(save_filtered_errors=True) + with watcher: + match_type, rest_type, captures = self.accept(o, t) + if not is_uninhabited(match_type): + self.msg.add_errors(watcher.filtered_errors()) match_types.append(match_type) rest_types.append(rest_type) if not is_uninhabited(match_type): diff --git a/test-data/unit/check-python310.test b/test-data/unit/check-python310.test index 33b952f48f49d..6e83784bd5d83 100644 --- a/test-data/unit/check-python310.test +++ b/test-data/unit/check-python310.test @@ -3236,6 +3236,32 @@ def f2(m: tuple[int] | tuple[str, str] | tuple[int, Unpack[tuple[str, ...]], int reveal_type(m) # N: Revealed type is "tuple[builtins.int, Unpack[builtins.tuple[builtins.str, ...]], builtins.int]" [builtins fixtures/tuple.pyi] +[case testMatchSequencePatternTupleUnionFalsePositiveUnreachable] +# flags: --strict-equality --warn-unreachable +from typing import Literal + +value: tuple[Literal["a"], None] | tuple[Literal["b"], int] = ("a", None) + +match value: + case "a", None: + pass + case _: + pass +[builtins fixtures/tuple.pyi] + +[case testMatchSequencePatternTupleUnionFalsePositiveUnreachableClassPattern] +# flags: --strict-equality --warn-unreachable +value: tuple[None, int] | tuple[int, None] | tuple[int, int] + +match value: + case None, int(y): + pass + case int(x), None: + pass + case int(x), int(y): + pass +[builtins fixtures/tuple.pyi] + [case testMatchSequencePatternTypeVarTupleNotTooShort] # flags: --strict-equality --warn-unreachable from typing import Tuple