multiple `nonlocal` declarations of the same variable

This commit is contained in:
Jack O'Connor 2025-07-09 18:30:41 -07:00
parent b31102a9ee
commit eb67413a3e
1 changed files with 20 additions and 1 deletions

View File

@ -301,10 +301,29 @@ Using a name prior to its `nonlocal` declaration in the same scope is a syntax e
def f():
x = 1
def g():
print(x)
x = 2
nonlocal x # error: [invalid-syntax] "name `x` is used prior to nonlocal declaration"
```
This is true even if there are multiple `nonlocal` declarations of the same variable, as long as any
of them come after the usage:
```py
def f():
x = 1
def g():
nonlocal x
x = 2
nonlocal x # error: [invalid-syntax] "name `x` is used prior to nonlocal declaration"
def f():
x = 1
def g():
nonlocal x
nonlocal x
x = 2 # allowed
```
## `nonlocal` before outer initialization
`nonlocal x` works even if `x` isn't bound in the enclosing scope until afterwards: