Python Reference ยท Statements and Keywords
The global and nonlocal statements
Reference for Python global and nonlocal: assign to module-level or enclosing-function variables, how scoping decides, and why to avoid global state.
Inside a function, assigning to a name normally creates a new local variable. The global and nonlocal statements change that: they tell Python that assignments to a name inside this function should rebind the existing variable in an outer scope instead.
global targets the module-level namespace. nonlocal targets the nearest enclosing function scope, which is what closures need to update a counter or accumulator.
count = 0 def bump(): global count count += 1
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
global name global name1, name2 nonlocal name nonlocal name1, name2
| Statement | Description |
|---|---|
global name |
Within this function, name refers to the module-level variable. Assigning rebinds it (creating it if needed). |
nonlocal name |
Within this function, name refers to the variable in the nearest enclosing function. It must already exist there. |
Both statements must come before the first use of the name in that function.
Raises: SyntaxError if nonlocal finds no enclosing binding, if the name is used before the declaration, or if a parameter has the same name. nonlocal at module level is a SyntaxError too.
Usage notes
- Reading needs no declaration. A function can read outer variables freely; the declaration matters only when you assign, augment (
+=),delor otherwise rebind the name. - Mutating is not rebinding.
items.append(x)orconfig["k"] = vchanges the object an outer name points to without anyglobalstatement. - Whole-function decision. If a function assigns to a name anywhere, that name is local throughout, so reading it before the assignment raises
UnboundLocalError. globalinside nested functions still means the module level, skipping intermediate function scopes.nonlocalstops at the nearest enclosing function.- Prefer alternatives. Pass values as arguments, return results, use a class with attributes, or a small mutable container. Global state makes code hard to test.
- Class bodies are not enclosing scopes for
nonlocalpurposes. - Constants in upper case at module level are fine to read from anywhere; just do not rebind them.
- Module attribute alternative.
import config; config.value = 3changes another module's global withoutglobal.