8000 Fix type inference in pattern matching by positional argument · python/mypy@7204ab1 · GitHub
[go: up one dir, main page]

Skip to content

Commit 7204ab1

Browse files
committed
Fix type inference in pattern matching by positional argument
1 parent 8eb9cdc commit 7204ab1

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

mypy/expandtype.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,8 @@ def visit_erased_type(self, t: ErasedType) -> Type:
136136
def visit_instance(self, t: Instance) -> Type:
137137
args = self.expand_types_with_unpack(list(t.args))
138138
if isinstance(args, list):
139-
return Instance(t.type, args, t.line, t.column)
139+
print(t)
140+
return t.copy_modified(args=args)
140141
else:
141142
return args
142143

test-data/unit/check-python310.test

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1628,3 +1628,49 @@ match var:
16281628
case ("yes", b):
16291629
reveal_type(b) # N: Revealed type is "Union[builtins.int, builtins.str]"
16301630
[builtins fixtures/tuple.pyi]
1631+
1632+
[case testMatchNamedAndKeywordsAreTheSame]
1633+
from typing import Generic, TypeVar, Union
1634+
from typing_extensions import Final
1635+
1636+
T = TypeVar("T")
1637+
1638+
class Regular:
1639+
x: str
1640+
y: int
1641+
__match_args__ = ("x",)
1642+
class ReveresedOrder:
1643+
x: int
1644+
y: str
1645+
__match_args__ = ("y",)
1646+
class GenericRegular(Generic[T]):
1647+
x: T
1648+
__match_args__ = ("x",)
1649+
class GenericWithFinal(Generic[T]):
1650+
x: T
1651+
__match_args__: Final = ("x",)
1652+
1653+
input_arg: Union[Regular, ReveresedOrder, GenericRegular[str], GenericWithFinal[str]]
1654+
1655+
# Positional:
1656+
match input_arg:
1657+
case Regular(a):
1658+
reveal_type(a) # N: Revealed type is "builtins.str"
1659+
case ReveresedOrder(a):
1660+
reveal_type(a) # N: Revealed type is "builtins.str"
1661+
case GenericRegular(a):
1662+
reveal_type(a) # N: Revealed type is "builtins.str"
1663+
case GenericWithFinal(a):
1664+
reveal_type(a) # N: Revealed type is "builtins.str"
1665+
1666+
# Keywords:
1667+
match input_arg:
1668+
case Regular(x=a):
1669+
reveal_type(a) # N: Revealed type is "builtins.str"
1670+
case ReveresedOrder(x=b): # note, that order is different
1671+
reveal_type(b) # N: Revealed type is "builtins.int"
1672+
case GenericRegular(x=a):
1673+
reveal_type(a) # N: Revealed type is "builtins.str"
1674+
case GenericWithFinal(x=a):
1675+
reveal_type(a) # N: Revealed type is "builtins.str"
1676+
[builtins fixtures/tuple.pyi]

0 commit comments

Comments
 (0)
0