`possibly-undefined` false positive with `global` statement inside `if`
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
The optional possibly-undefined error gives a false positive on this code with a global statement inside an if branch. At runtime, Python treats global as applying unconditionally for the entire function scope, but mypy seems to think it only applies to the branch.
To Reproduce
# mypy: enable-error-code="possibly-undefined"
g = 1
def f(b: bool) -> None:
if b:
global g
g = 2
print(g) # error: Name "g" may be undefined [possibly-undefined]
Expected Behavior
No error.
Actual Behavior
main.py:10: error: Name "g" may be undefined [possibly-undefined]
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used: 1.4.1
- Mypy command-line flags:
--enable-error-code=possibly-undefined - Mypy configuration options from
mypy.ini(and other config files): none - Python version used: 3.10.12
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the report with the provided Python snippet and the possibly-undefined error code, then trace how mypy handles the global statement inside the if branch. Done means the example produces no false-positive error for g after the branch, while genuine possibly-undefined cases remain diagnosed.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100