Learning navigation

Code with Animation

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.

Python7 min readConcept 11 of 24

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.

Select Variable Lookup Target:
# 1. Scoped namespaces:
z = "global_z" [G]
def outer():
y = "enclosing_y" [E]
def inner():
x = "local_x" [L]
# 2. Variable lookup statement:
return x
# [L] Matched x immediately!
THE LEGB SCOPE LOOKUP RADAR[B] BUILT-IN SCOPE: len, range, print, int[G] GLOBAL (MODULE) SCOPE: z = "global_z"[E] ENCLOSING (OUTER) SCOPE: y = "enclosing_y"[L] LOCAL (INNER) SCOPE COREx = "local_x"First namespace checked on every variable lookupLOOKUP RESOLUTION PATHWAY:Found immediately in [L] Local Scope @ core (1 hop)
★ Python Rule: Variable lookups always proceed outward in order: Local → Enclosing → Global → Built-in. Any assignment inside a function marks that variable local for the entire function.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1In what order does Python search namespaces when looking up an unqualified variable name?
  2. 2What causes `UnboundLocalError: local variable 'count' referenced before assignment`?
  3. 3Which keyword allows an inner nested function to reassign a variable belonging to its immediate outer function?

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.