diff --git a/mypy/checkpattern.py b/mypy/checkpattern.py index 4b34c0ddb54b..2a8620482d87 100644 --- a/mypy/checkpattern.py +++ b/mypy/checkpattern.py @@ -54,7 +54,7 @@ get_proper_type, split_with_prefix_and_suffix, ) -from mypy.typevars import fill_typevars +from mypy.typevars import fill_typevars, fill_typevars_with_any from mypy.visitor import PatternVisitor self_match_type_names: Final = [ @@ -544,16 +544,7 @@ def visit_class_pattern(self, o: ClassPattern) -> PatternType: self.msg.fail(message_registry.CLASS_PATTERN_GENERIC_TYPE_ALIAS, o) return self.early_non_match() if isinstance(type_info, TypeInfo): - any_type = AnyType(TypeOfAny.implementation_artifact) - args: list[Type] = [] - for tv in type_info.defn.type_vars: - if isinstance(tv, TypeVarTupleType): - args.append( - UnpackType(self.chk.named_generic_type("builtins.tuple", [any_type])) - ) - else: - args.append(any_type) - typ: Type = Instance(type_info, args) + typ: Type = fill_typevars_with_any(type_info) elif isinstance(type_info, TypeAlias): typ = type_info.target elif ( @@ -703,6 +694,8 @@ def visit_class_pattern(self, o: ClassPattern) -> PatternType: def should_self_match(self, typ: Type) -> bool: typ = get_proper_type(typ) + if isinstance(typ, TupleType): + typ = typ.partial_fallback if isinstance(typ, Instance) and typ.type.get("__match_args__") is not None: # Named tuples and other subtypes of builtins that define __match_args__ # should not self match. diff --git a/test-data/unit/check-python310.test b/test-data/unit/check-python310.test index 0ba7ffc82eca..016f50552a5f 100644 --- a/test-data/unit/check-python310.test +++ b/test-data/unit/check-python310.test @@ -770,6 +770,21 @@ match m: reveal_type(j) # N: Revealed type is "builtins.int" [builtins fixtures/tuple.pyi] +[case testMatchSequencePatternCaptureNamedTuple] +from typing import NamedTuple + +class N(NamedTuple): + x: int + y: str + +a = N(1, "a") + +match a: + case [x, y]: + reveal_type(x) # N: Revealed type is "builtins.int" + reveal_type(y) # N: Revealed type is "builtins.str" +[builtins fixtures/tuple.pyi] + [case testMatchClassPatternCaptureGeneric] from typing import Generic, TypeVar @@ -2522,3 +2537,18 @@ def fn2(x: Some | int | str) -> None: case Some(value): # E: Incompatible types in capture pattern (pattern captures type "Union[int, str]", variable has type "Callable[[], str]") pass [builtins fixtures/dict.pyi] + +[case testMatchNamedTupleSequence] +from typing import Any, NamedTuple + +class T(NamedTuple): + t: list[Any] + +class K(NamedTuple): + k: int + +def f(t: T) -> None: + match t: + case T([K() as k]): + reveal_type(k) # N: Revealed type is "Tuple[builtins.int, fallback=__main__.K]" +[builtins fixtures/tuple.pyi]