python / python/mypy

`possibly-undefined` false positive with `global` statement inside `if`

Open
#15,838 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-possibly-undefined
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]

Playground

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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.