nonlocal Nonlocal declaration
Last updated: 2026-09-22
nonlocal Nonlocal declaration
nonlocal name refers to the nearest enclosing scope's variable (not global).
| Category | Keywords & Statements |
|---|---|
| Kind | Keyword / Statement |
| Python Version | all |
📝 Syntax
nonlocal name [, name]*
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
1 2
🏷️ Related Keywords / Statements
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QWhat happens if I modify an outer variable inside a nested function without `nonlocal`?
AIt creates a same-named local variable in the inner function; the outer variable's value is unchanged, and you may even get `UnboundLocalError`. To modify the outer variable, you must declare `nonlocal` first.
QCan `nonlocal` point to a global variable?
ANo. `nonlocal` must bind to a variable that already exists in some enclosing function scope. If there is no such variable, you get `SyntaxError: no binding for nonlocal 'x' found`.
QCan `nonlocal` and `global` be used together?
AYes, but only for different names. The same name cannot be declared both `global` and `nonlocal`; doing so raises a `SyntaxError`.