pyright icon indicating copy to clipboard operation
pyright copied to clipboard

Improve match subject narrowing

Open cdce8p opened this issue 6 months ago • 0 comments

Is your feature request related to a problem? Please describe. At the moment type narrowing after a match case pattern only seems to be applied to bound variables. It would be great if the same information could also be mapped to the match subject itself similar to how it is with isinstance calls. This would especially help with building and debugging match statements where I found it's common to go layer by layer until the pattern is complete and only then bind variables if necessary.

import ast

def func(case: ast.match_case) -> None:
    match case.pattern:
        case ast.MatchAs(pattern=None as p, name=str() as n):
            reveal_type(case.pattern)  # ast.MatchAs
            reveal_type(case.pattern.pattern)  # should be 'None', not 'pattern | None'
            reveal_type(p)  # None
            reveal_type(case.pattern.name)  # should be 'str', not 'str | None'
            reveal_type(n)  # str

    if (
        isinstance(case.pattern, ast.MatchAs)
        and case.pattern.pattern is None
        and isinstance(case.pattern.name, str)
    ):
        reveal_type(case.pattern.pattern)  # None
        reveal_type(case.pattern.name)  # str

This is also an issue with the latest mypy release. Though the implementation was mostly strait forward. My PR also contains a few more test cases https://github.com/python/mypy/pull/19736.

-- pyright 1.1.404

cdce8p avatar Aug 27 '25 12:08 cdce8p