microsoft / microsoft/pyright

Improve match subject narrowing

Open
#10,853 0 comments 1 reaction 0 assignees View on GitHub
enhancement request
Dominant language
Python
Stars
15.6k
Forks
1.8k
Avg merge
12h 13m
Merged PRs (30d)
52

Description

**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.

```py
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

Contributor guide

Open the contributing guide

Research direction

Start with the match-case and reveal_type examples in the issue, then inspect the linked mypy pull request for related implementation and test cases. The work is done when narrowing is also reflected on the match subject and its attributes, including the demonstrated None and str types, with corresponding tests in pyright.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.