Phase 4 of 25 · Topic 4.1

LEGB Scope Resolution Rule (Local, Enclosing, Global, Built-in)

1Concept

Python resolves variable names following the strict LEGB order: 1. Local (inside current function); 2. Enclosing (inside outer enclosing functions in closures); 3. Global (module-level namespace); 4. Built-in (`builtins` module containing len, range, print). If not found in any scope, a `NameError` is raised.

2Architecture Diagram

LEGB Scope Search Hierarchy:
[ Local Scope ] ---> [ Enclosing Scope ] ---> [ Global Scope ] ---> [ Built-in Scope ] ---> NameError!

3Code Example

Python 3.12
x = "GLOBAL"

def outer():
    x = "ENCLOSING"
    def inner():
        x = "LOCAL"
        print(f"Inside inner: {x}")
    inner()
    print(f"Inside outer: {x}")

outer()
print(f"Module scope: {x}")

4Expected Output

Inside inner: LOCAL
Inside outer: ENCLOSING
Module scope: GLOBAL

5Key Takeaways

  • LEGB is checked from innermost to outermost scope.
  • Assigning to a variable inside a function makes it local unless declared `global` or `nonlocal`.
  • Shadowing built-ins (e.g. `list = [1, 2]`) breaks subsequent calls to the built-in function.