Skip to content

Commit 54a2c6d

Browse files
Fix type inference of positional parameter in class pattern involving builtin subtype (#18141)
Fixes #18140 ### Demo ```python from typing import reveal_type class A(str): pass class B(str): __match_args__ = ("b",) @Property def b(self) -> int: return 1 match A("a"): case A(a): reveal_type(a) # before: Revealed type is "__main__.A" # after: Revealed type is "__main__.A" print(type(a)) # output: <class '__main__.A'> match B("b"): case B(b): reveal_type(b) # before: Revealed type is "__main__.B" # after: Revealed type is "builtins.int" print(type(b)) # output: <class 'int'> ```
1 parent 3b00002 commit 54a2c6d

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

mypy/checkpattern.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -693,7 +693,9 @@ def visit_class_pattern(self, o: ClassPattern) -> PatternType:
693693

694694
def should_self_match(self, typ: Type) -> bool:
695695
typ = get_proper_type(typ)
696-
if isinstance(typ, Instance) and typ.type.is_named_tuple:
696+
if isinstance(typ, Instance) and typ.type.get("__match_args__") is not None:
697+
# Named tuples and other subtypes of builtins that define __match_args__
698+
# should not self match.
697699
return False
698700
for other in self.self_match_types:
699701
if is_subtype(typ, other):

test-data/unit/check-python310.test

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -648,6 +648,25 @@ match m:
648648
reveal_type(m) # N: Revealed type is "builtins.tuple[Any, ...]"
649649
[builtins fixtures/primitives.pyi]
650650

651+
[case testMatchClassPatternCaptureSelfSubtype]
652+
class A(str):
653+
pass
654+
655+
class B(str):
656+
__match_args__ = ("b",)
657+
b: int
658+
659+
def f1(x: A):
660+
match x:
661+
case A(a):
662+
reveal_type(a) # N: Revealed type is "__main__.A"
663+
664+
def f2(x: B):
665+
match x:
666+
case B(b):
667+
reveal_type(b) # N: Revealed type is "builtins.int"
668+
[builtins fixtures/tuple.pyi]
669+
651670
[case testMatchInvalidClassPattern]
652671
m: object
653672

0 commit comments

Comments
 (0)