diff --git a/mypy/checker.py b/mypy/checker.py index 6d7e8fa215a1..c9e0dcec6bd0 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -5527,6 +5527,8 @@ def visit_match_stmt(self, s: MatchStmt) -> None: pattern_map, else_map = conditional_types_to_typemaps( named_subject, pattern_type.type, pattern_type.rest_type ) + pattern_map = self.propagate_up_typemap_info(pattern_map) + else_map = self.propagate_up_typemap_info(else_map) self.remove_capture_conflicts(pattern_type.captures, inferred_types) self.push_type_map(pattern_map, from_assignment=False) if pattern_map: diff --git a/test-data/unit/check-python310.test b/test-data/unit/check-python310.test index 016f50552a5f..18554a3540e6 100644 --- a/test-data/unit/check-python310.test +++ b/test-data/unit/check-python310.test @@ -332,6 +332,54 @@ match [SubClass("a"), SubClass("b")]: reveal_type(rest) # N: Revealed type is "builtins.list[__main__.Example]" [builtins fixtures/tuple.pyi] +# Narrowing union-based values via a literal pattern on an indexed/attribute subject +# ------------------------------------------------------------------------------- +# Literal patterns against a union of types can be used to narrow the subject +# itself, not just the expression being matched. Previously, the patterns below +# failed to narrow the `d` variable, leading to errors for missing members; we +# now propagate the type information up to the parent. + +[case testMatchNarrowingUnionTypedDictViaIndex] +from typing import Literal, TypedDict + +class A(TypedDict): + tag: Literal["a"] + name: str + +class B(TypedDict): + tag: Literal["b"] + num: int + +d: A | B +match d["tag"]: + case "a": + reveal_type(d) # N: Revealed type is "TypedDict('__main__.A', {'tag': Literal['a'], 'name': builtins.str})" + reveal_type(d["name"]) # N: Revealed type is "builtins.str" + case "b": + reveal_type(d) # N: Revealed type is "TypedDict('__main__.B', {'tag': Literal['b'], 'num': builtins.int})" + reveal_type(d["num"]) # N: Revealed type is "builtins.int" +[typing fixtures/typing-typeddict.pyi] + +[case testMatchNarrowingUnionClassViaAttribute] +from typing import Literal + +class A: + tag: Literal["a"] + name: str + +class B: + tag: Literal["b"] + num: int + +d: A | B +match d.tag: + case "a": + reveal_type(d) # N: Revealed type is "__main__.A" + reveal_type(d.name) # N: Revealed type is "builtins.str" + case "b": + reveal_type(d) # N: Revealed type is "__main__.B" + reveal_type(d.num) # N: Revealed type is "builtins.int" + [case testMatchSequenceUnion-skip] from typing import List, Union m: Union[List[List[str]], str]