Skip to content

Commit 883b866

Browse files
Fix generic NamedTuple class pattern matching
1 parent bdef6ef commit 883b866

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

mypy/checkpattern.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -722,6 +722,8 @@ def get_class_pattern_type_ranges(self, typ: Type, o: ClassPattern) -> list[Type
722722

723723
if isinstance(p_typ, FunctionLike) and p_typ.is_type_obj():
724724
typ = fill_typevars_with_any(p_typ.type_object())
725+
if isinstance(typ, TupleType) and typ.partial_fallback.type.is_named_tuple:
726+
typ = typ.partial_fallback
725727
return [TypeRange(typ, is_upper_bound=False)]
726728
if (
727729
isinstance(o.class_ref.node, Var)

test-data/unit/check-python310.test

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -961,6 +961,22 @@ match m:
961961
reveal_type(m) # N: Revealed type is "__main__.A[builtins.int]"
962962
reveal_type(i) # N: Revealed type is "builtins.int"
963963

964+
[case testMatchClassPatternCaptureGenericNamedTupleAlreadyKnown]
965+
from typing import Generic, NamedTuple, TypeVar
966+
967+
T = TypeVar("T")
968+
969+
class A(NamedTuple, Generic[T]):
970+
a: T
971+
972+
m: A[int]
973+
974+
match m:
975+
case A(a=i):
976+
reveal_type(i) # N: Revealed type is "builtins.int"
977+
[builtins fixtures/tuple.pyi]
978+
[typing fixtures/typing-namedtuple.pyi]
979+
964980
[case testMatchClassPatternCaptureFilledGenericTypeAlias]
965981
from typing import Generic, TypeVar
966982

test-data/unit/check-python312.test

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1676,6 +1676,20 @@ e: M[bool] # E: Value of type variable "T" of "M" cannot be "bool"
16761676
[builtins fixtures/tuple.pyi]
16771677
[typing fixtures/typing-full.pyi]
16781678

1679+
[case testMatchClassPatternCapturePEP695GenericNamedTupleAlreadyKnown]
1680+
from typing import NamedTuple
1681+
1682+
class N[T](NamedTuple):
1683+
x: T
1684+
1685+
n: N[int]
1686+
1687+
match n:
1688+
case N(x=value):
1689+
reveal_type(value) # N: Revealed type is "builtins.int"
1690+
[builtins fixtures/tuple.pyi]
1691+
[typing fixtures/typing-full.pyi]
1692+
16791693
[case testPEP695GenericTypedDict]
16801694
from typing import TypedDict
16811695

0 commit comments

Comments
 (0)