Improve syntax error for nonlocal not in a nested function
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 36k
- PR merge metrics
- PR metrics pending
Description
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.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by locating the compiler handling of nonlocal errors and the regression tests for invalid nested-function scope. Verify the existing message for a non-nested function, then make the completed behavior report the missing surrounding function and suggest global instead.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100