microsoft / microsoft/pyright

Local variables in unused code are not detected

Open
#11,449 0 comments 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

Note: if you are reporting a wrong signature of a function or a class in the standard library, then the typeshed tracker is better suited for this report: https://github.com/python/typeshed/issues.

If you have a question about typing or a behavior that you’re seeing in Pyright (as opposed to a bug report or enhancement request), consider posting to the [Pyright discussion forum](https://github.com/microsoft/pyright/discussions).

**Describe the bug**
When defining a function, Python checks each function's assignments. If a variable is ever assigned to, it is declared a local variable. Because this is checked at the time the function is defined, as opposed to when ran, local variables are created even when the code is unused. However, Pyright does not consider declarations in unused code to make the variable local.

**Code or Screenshots**
```python
>>> variable = "global"

def example_with_local():
return variable # should say "variable" is unbound (reportUnboundVariable)
variable = "local"

def example_without_local():
return variable

>>> example_with_local.__code__.co_varnames
('variable',)
>>> example_with_local.__code__.co_nlocals
1
>>> example_with_local()
UnboundLocalError: cannot access local variable 'variable' where it is not associated with a value

def example_without_local():
return variable
>>> example_without_local.__code__.co_varnames
()
>>> example_without_local.__code__.co_nlocals
0
>>> example_without_local()
'global'
```

Pyright incorrectly determines that the functions are identical, and does not emit an error.

This can also lead to false positives:

```python
def outer():
def inner():
nonlocal variable # Pyright error: No binding for nonlocal "variable" found

return
variable = "local"
```

**VS Code extension or command-line**
VSCode extension version 1.1.402

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the two function examples and the nested nonlocal example from the issue, then trace Pyright's analysis of assignments in unused code. Done means reporting variable as unbound when an unreachable assignment makes it local, while avoiding the incorrect nonlocal binding error in the nested case.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.