python / python/mypy

New semantic analyzer: Explain that global variable must be declared at module top level

Open
#6,976 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

priority-1-normal semantic-analyzer topic-usability
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

The error message is poor for code like this where we don't initialize or declare a global variable at the module top level:

from typing import List


def foo() -> None:
    global bar
    bar = []  # type: List[str]  # Name 'bar' already defined (possibly by an import)
    bar  # Name 'bar' is not defined

It would be better to be explicit and say something like "Global variable must be declared or initialized at module top level".

Follow-up to #6975.

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

Start with the semantic analyzer handling global declarations and reproduce the Python snippet from the issue. Update the diagnostic so this case explains that the global variable must be declared or initialized at module top level, then verify that the reported message matches the requested wording.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.