Skip to content

More specific type inference from structural pattern matching #16657

Description

@Doekeb

Feature

Mypy should take a note from Pylance and infer more specific types as a result of structural pattern matching.

Pitch

The main example:

class Parent:
pass
class A(Parent):
def do_something(self) -> None:
print("something A-ish")
class B(Parent):
def do_something(self) -> None:
print("something B-ish")
def my_function(val: Parent) -> None:
match val:
case A():
pass
case B():
pass
case Parent():
return
val.do_something() # "Parent" has no attribute "do_something" Mypy(attr-defined)
reveal_type(val)

The result of reveal_type(val) is Parent according to Mypy and A | B according to Pylance. While both of these correctly describe the type of val, the type of A | B is more specific which means the type checker would have no reason to complain about val.do_something().

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions