X Tutup
The Wayback Machine - https://web.archive.org/web/20220612141759/https://github.com/python/cpython/issues/92989
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve syntax error for nonlocal not in a nested function #92989

Open
stevendaprano opened this issue May 19, 2022 · 0 comments
Open

Improve syntax error for nonlocal not in a nested function #92989

stevendaprano opened this issue May 19, 2022 · 0 comments
Labels
interpreter-core type-feature

Comments

@stevendaprano
Copy link
Member

@stevendaprano stevendaprano commented May 19, 2022

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.

@stevendaprano stevendaprano added the type-feature label May 19, 2022
@erlend-aasland erlend-aasland added the interpreter-core label May 19, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
interpreter-core type-feature
Projects
None yet
Development

No branches or pull requests

2 participants
X Tutup