microsoft / microsoft/pyright

Inconsistent local variable narrowing for `finally` block

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

Description

Consider the following:

```python
x = None
try:
x = 5
finally:
print(x)
reveal_type(x) # Literal[5] | None
```

If I change `print(x)` to `print(None)`, the revealed type changes.

This is due to a bad interaction between the handling of the "finally gate" in the code flow graph and an code flow optimization that skips blocks if the expression is not referenced. If `x` is not referenced in the `finally` block, we get a different answer.

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the issue's Python snippet and comparing the revealed types with and without the reference in the finally block. Trace the interaction between the finally gate in the code flow graph and the optimization that skips unreferenced expressions; done means both forms produce consistent narrowing.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
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.