Variable Scope & the LEGB Rule
Master the Python namespace lookup hierarchy: the LEGB rule (Local, Enclosing, Global, Built-in), lexical closures, the global and nonlocal keywords, and diagnosing UnboundLocalError.
The LEGB Lookup Rule
A scope is a textual region of a Python program where a namespace is directly accessible. When Python encounters a variable name, it searches four nested namespaces in a strict deterministic order known as the LEGB rule:
1. Local (L): Names assigned or declared inside the current function body.
2. Enclosing (E): Names in the local scope of any enclosing/outer functions (relevant in nested functions and closures), searched from the nearest inner function outward.
3. Global (G): Names assigned at the top-level of the current module file, or declared using global inside a function.
4. Built-in (B): Python pre-loaded module (builtins) containing built-in functions and exceptions like len(), range(), int(), and ValueError.
Modifying Outer Scopes: global and nonlocal
Reading outer variables happens automatically through the LEGB rule. However, assigning to a variable inside a function creates a new local variable by default, shadowing any identically-named variable in an outer scope.
To modify a module-level variable from inside a function, declare it with the global keyword: global counter.
In nested functions, to rebind a variable that belongs to an enclosing outer function (without making it global), declare it with the nonlocal keyword: nonlocal counter. This is foundational for stateful closures.
Closures and Encapsulated State
A closure occurs when an inner function retains access to variables from its enclosing scope even after the outer function has finished executing and its stack frame has returned.
For example, a generator function def make_counter(): count = 0; def inc(): nonlocal count; count += 1; return count; return inc packages the count variable inside the returned function's __closure__ attribute.
Closures provide lightweight data encapsulation without needing to write a full class.
The LEGB Scope Lookup Radar
Scan outward through Local, Enclosing, Global, and Built-in namespaces. Observe how variable names resolve at each boundary or trigger an UnboundLocalError.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Python resolves variable names following the LEGB rule: Local -> Enclosing -> Global -> Built-in.
- Assigning to a variable inside a function automatically makes it local for the entire function body.
- Use nonlocal to rebind variables in an enclosing outer function within a closure.
- UnboundLocalError happens when code reads a variable before assigning to it in a function that contains an assignment to that same name.
Done with this concept?
Mark it complete to track your progress. No login needed.