python / python/mypy

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

Aperta
#12,747 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug topic-variable-scope
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia da SemanticAnalyzer.visit_global_decl ed esamina come vengono controllate le tabelle correnti locals, global e nonlocal. Segui la ricerca dei nomi per gli esempi x e y, incluso il caso della variabile libera, e determina come le dichiarazioni dovrebbero rilevare gli utilizzi precedenti. Il lavoro è completato quando mypy segnala le dichiarazioni global e nonlocal non valide mostrate.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
compilers
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.