microsoft / microsoft/pyright

Shadowing names in cases of a match with non-trivial scrutinee

Open
#10,632 1 comment 0 reactions 0 assignees View on GitHub
bug
Dominant language
Python
Stars
15.6k
Forks
1.8k
Avg merge
12h 13m
Merged PRs (30d)
52

Description

**Code**
```python
from typing import Literal
from collections.abc import Mapping

type Ty = (
tuple[Literal["var"], str] |
str
)

type Sub = Mapping[str, Ty]

def unify(a: Ty, b: Ty) -> Sub:
match a, b:
case ("var", a), b:
# a is narrowed to tuple[Literal["var", str]] when its really a `str` (both making this well-typed program not typecheck, and allowing absurd programs)
return {a: b}
case _:
assert a == b
return {}

def trivial_scrutinee(a: Ty) -> str:
match a:
case ("var", a):
# shadowed correctly
return a
case _:
raise ValueError

def nontrivial_scrutinee(a: Ty) -> str:
match a, None:
case ("var", a), _:
# a: tuple[Literal["var"], str] so it doesnt typecheck
return a
case _:
raise ValueError
```

**Expected behavior and questions**
In `unify` i expected the type of `a` to get shadowed to `str`, but i guess that python typecheckers usually dont like mid-scope shadowing?
But in this specific case, the `case` is "closed" by a return statement, so it does not affect the type of `a` in code after the match, so i'd expect it to be fine
What's pyright's stance on shadowing in general? Is it documented somewhere? I couldn't find it by ctrl-f'ing "shadowing" in https://microsoft.github.io/pyright/#/type-concepts-advanced

**VS Code extension or command-line**
VSCode and CLI, pyright 1.1.402

Contributor guide

Open the contributing guide

Research direction

Reproduce the supplied examples with pyright 1.1.402 through the VS Code extension or command line, comparing the trivial and non-trivial scrutinees. Read the resulting diagnostics and type narrowing around each match case; done means the shadowing behavior and its intended documentation or correction are agreed and verified against these examples.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.