Skip to content

Commit

Permalink
Fix type inference in pattern matching by positional argument
Browse files Browse the repository at this point in the history
  • Loading branch information
sobolevn committed Sep 7, 2022
1 parent 8eb9cdc commit 2f4bd29
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
2 changes: 1 addition & 1 deletion mypy/expandtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ def visit_erased_type(self, t: ErasedType) -> Type:
def visit_instance(self, t: Instance) -> Type:
args = self.expand_types_with_unpack(list(t.args))
if isinstance(args, list):
return Instance(t.type, args, t.line, t.column)
return t.copy_modified(args=args)
else:
return args

Expand Down
46 changes: 46 additions & 0 deletions test-data/unit/check-python310.test
Original file line number Diff line number Diff line change
Expand Up @@ -1628,3 +1628,49 @@ match var:
case ("yes", b):
reveal_type(b) # N: Revealed type is "Union[builtins.int, builtins.str]"
[builtins fixtures/tuple.pyi]

[case testMatchNamedAndKeywordsAreTheSame]
from typing import Generic, TypeVar, Union
from typing_extensions import Final

T = TypeVar("T")

class Regular:
x: str
y: int
__match_args__ = ("x",)
class ReveresedOrder:
x: int
y: str
__match_args__ = ("y",)
class GenericRegular(Generic[T]):
x: T
__match_args__ = ("x",)
class GenericWithFinal(Generic[T]):
x: T
__match_args__: Final = ("x",)

input_arg: Union[Regular, ReveresedOrder, GenericRegular[str], GenericWithFinal[str]]

# Positional:
match input_arg:
case Regular(a):
reveal_type(a) # N: Revealed type is "builtins.str"
case ReveresedOrder(a):
reveal_type(a) # N: Revealed type is "builtins.str"
case GenericRegular(a):
reveal_type(a) # N: Revealed type is "builtins.str"
case GenericWithFinal(a):
reveal_type(a) # N: Revealed type is "builtins.str"

# Keywords:
match input_arg:
case Regular(x=a):
reveal_type(a) # N: Revealed type is "builtins.str"
case ReveresedOrder(x=b): # note, that order is different
reveal_type(b) # N: Revealed type is "builtins.int"
case GenericRegular(x=a):
reveal_type(a) # N: Revealed type is "builtins.str"
case GenericWithFinal(x=a):
reveal_type(a) # N: Revealed type is "builtins.str"
[builtins fixtures/tuple.pyi]

0 comments on commit 2f4bd29

Please sign in to comment.