nonlocalPython variable scope decides which regions of your program can read or modify a name. Whenever you reference a variable, Python searches four nested levels in exact order: Local, Enclosing, Global, and Built-in (the LEGB rule).
Understanding scope stops confusing bugs like UnboundLocalError and shows why functions stay safer when they take inputs as arguments rather than mutating globals.
flowchart TD
L["1. Local (current function)"] --> E["2. Enclosing (outer function)"]
E --> G["3. Global (module top level)"]
G --> B["4. Built-in (len, print, int)"]
If Python finds the name in Local scope, it stops searching immediately. A closure happens when an inner function remembers variables from its Enclosing scope even after the outer function returns.
tax_rate = 0.08 # Global scope
def make_counter(start: int = 0):
count = start # Enclosing scope
def step() -> int:
nonlocal count
count += 1
return count
return step
counter = make_counter(10)
print(counter(), counter()) # 11 12
global vs nonlocalnonlocal lets a nested function rebind a variable in its enclosing function, while global lets a function rebind a module-level variable. Avoid global in production code; pass parameters and return values instead.
UnboundLocalError: Assigning x = x + 1 inside a function without global or nonlocal makes Python treat x as local before it exists.list = [1, 2] hides Python's built-in list() everywhere in that scope.if or for blocks to create a new scope: Only functions, classes, and modules create scopes in Python; loop variables remain visible after a for loop ends.if statements or for loops create local scopes in Python?No. A variable assigned inside an if block or for loop belongs to the surrounding function or module scope.
Closures work cleanly for decorators, factory functions, and lightweight stateful callbacks where writing a full class feels heavy.
Call locals() inside a function or globals() at module level to see a dictionary of bound names.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.