Skip to content

Commit 3d37c29

Browse files
committed
Fix handling of named tuples in class match pattern
1 parent 44f82ef commit 3d37c29

File tree

2 files changed

+19
-11
lines changed

2 files changed

+19
-11
lines changed

mypy/checkpattern.py

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@
5454
get_proper_type,
5555
split_with_prefix_and_suffix,
5656
)
57-
from mypy.typevars import fill_typevars
57+
from mypy.typevars import fill_typevars, fill_typevars_with_any
5858
from mypy.visitor import PatternVisitor
5959

6060
self_match_type_names: Final = [
@@ -544,16 +544,7 @@ def visit_class_pattern(self, o: ClassPattern) -> PatternType:
544544
self.msg.fail(message_registry.CLASS_PATTERN_GENERIC_TYPE_ALIAS, o)
545545
return self.early_non_match()
546546
if isinstance(type_info, TypeInfo):
547-
any_type = AnyType(TypeOfAny.implementation_artifact)
548-
args: list[Type] = []
549-
for tv in type_info.defn.type_vars:
550-
if isinstance(tv, TypeVarTupleType):
551-
args.append(
552-
UnpackType(self.chk.named_generic_type("builtins.tuple", [any_type]))
553-
)
554-
else:
555-
args.append(any_type)
556-
typ: Type = Instance(type_info, args)
547+
typ: Type = fill_typevars_with_any(type_info)
557548
elif isinstance(type_info, TypeAlias):
558549
typ = type_info.target
559550
elif (
@@ -703,6 +694,8 @@ def visit_class_pattern(self, o: ClassPattern) -> PatternType:
703694

704695
def should_self_match(self, typ: Type) -> bool:
705696
typ = get_proper_type(typ)
697+
if isinstance(typ, TupleType):
698+
typ = typ.partial_fallback
706699
if isinstance(typ, Instance) and typ.type.get("__match_args__") is not None:
707700
# Named tuples and other subtypes of builtins that define __match_args__
708701
# should not self match.

test-data/unit/check-python310.test

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2522,3 +2522,18 @@ def fn2(x: Some | int | str) -> None:
25222522
case Some(value): # E: Incompatible types in capture pattern (pattern captures type "Union[int, str]", variable has type "Callable[[], str]")
25232523
pass
25242524
[builtins fixtures/dict.pyi]
2525+
2526+
[case testMatchNamedTupleSequence]
2527+
from typing import Any, NamedTuple
2528+
2529+
class T(NamedTuple):
2530+
t: list[Any]
2531+
2532+
class K(NamedTuple):
2533+
k: int
2534+
2535+
def f(t: T) -> None:
2536+
match t:
2537+
case T([K() as k]):
2538+
reveal_type(k) # N: Revealed type is "Tuple[builtins.int, fallback=__main__.K]"
2539+
[builtins fixtures/tuple.pyi]

0 commit comments

Comments
 (0)