python / python/mypy

Does not report syntax error for global/nonlocal declaration after the name is used.

Open
#12,747 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-variable-scope
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

In this example:

def f():
	print(x)
	x = 2
	global x
	print(y)
	global y
def f2():
	x = y = 0
	def g():
		print(x)
		x = 2
		nonlocal x
		print(y)
		nonlocal y

Running mypy reports no errors. However, the uses of x and y are all syntax errors.

SemanticAnalyzer.visit_global_decl does not check for prior use of the name at all. It would find x the self.locals[-1] table. SemanticAnalyzer.visit_global_decl does check this table. However looking here is not sufficient for y, which is a free variable at this point in the program.

I would suggest that the analyzer keep track of free variables in the current scope, just as it does for global and nonlocal declarations. Every name appearing in the outer block is exactly one of (global, nonlocal, free, or local). If a name is bound (meaning it is not nonlocal or global), it is discarded from the free variables if it is there. If any simple name lookup doesn't find the name in the current scope, it will be added to the free variables, along with the node (if any) where the lookup found it in some other scope. Then, any global/nonlocal declaration can look in any of these 4 places; the declaration is valid if it is not found there, or is found as the same kind of name.

  • Mypy version used: 0.950
  • Python version used: 3.7

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 at SemanticAnalyzer.visit_global_decl and examine how the current locals, global, and nonlocal tables are checked. Trace name lookup for the x and y examples, including the free-variable case, and determine how declarations should detect earlier uses. Done means mypy reports the demonstrated invalid global and nonlocal declarations.

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
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.