python / python/cpython

Improve syntax error for nonlocal not in a nested function

Offen
#92,989 2 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

interpreter-core type-feature
Vorherrschende Sprache
Python
Sterne
77.2k
Forks
36k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Using nonlocal inside a non-nested function to refer to a global gives the syntax error "no binding for nonlocal 'name' found" even if the global 'name' exists. This is confusing. Improve the error message by making it clear that the problem is not that variable 'name' doesn't exist, but that the function is not nested inside another function containing a variable 'name'.

Suggestion: if nonlocal is used in a non-nested function where there is no surrounding function (e.g. either a global level function or one defined inside a class), rather than reporting that there is no binding found, make the error message more specific:

"nonlocal can only be used in function nested inside another function; perhaps try global instead?"

As evidence that this error message is not clear, see #92983 where the submitter @snoopyjc was mislead into thinking that the problem was the loop variable rather than the lack of nested function.

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne damit, die Compiler-Behandlung von nonlocal-Fehlern und die Regressionstests für ungültige Bereiche verschachtelter Funktionen zu finden. Überprüfe die bestehende Meldung für eine nicht verschachtelte Funktion und ändere anschließend das endgültige Verhalten so, dass die fehlende umgebende Funktion gemeldet und stattdessen global vorgeschlagen wird.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
compilers
Issue-Typ
Bug
Schwierigkeit
3/5
Geschätzter Aufwand
1-2 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
45/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.