5.2 Scope, The LEGB Rule, global/nonlocal & Closures
Understand where variables live and die! Visualize Python's LEGB scope rings, avoid UnboundLocalError, and learn how closures remember outer variables (the secret behind decorators).
1. What Is Scope? (The Room-Visibility Analogy)
Imagine an office building:
- A sticky note on your desk (Local) is private to your function — once your function finishes, your desk is wiped clean.
- A whiteboard in the main hallway (Global) can be read by anyone in the file.
Whenever Python sees a variable name like x, it searches outward in strict LEGB order:
Local → Enclosing → Global → Built-in!
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print("Inside inner:", x) # Finds 'local' first!
inner()
print("Inside outer:", x) # Finds 'enclosing'
outer()
print("At top level:", x) # Finds 'global'
2. The Classic UnboundLocalError Trap
Inside a function, you can read a global variable freely — but the moment you assign to it (count += 1), Python treats it as a brand-new LOCAL variable!
count = 0
def broken():
# ✗ Crashes with UnboundLocalError: cannot access local variable 'count'
count += 1
# ✓ Better design: pass values in and return the updated result!
def increment(count):
return count + 1
count = increment(count) # Clean, testable, zero hidden global state!
(Python also has the global keyword to mutate a global variable, and nonlocal to mutate an enclosing variable — use global sparingly in real code because shared global state causes hard-to-trace bugs.)
3. Closures: Functions That Remember Their Birthplace
In Python, functions can create and return other functions. When an inner function remembers a variable from its outer (Enclosing) function even after the outer function has finished, that's called a Closure!
def make_multiplier(factor):
def multiply(number):
return number * factor # Remembers `factor` from Enclosing scope!
return multiply
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(10)) # 20
print(triple(10)) # 30
Why closures matter: Closures are the exact mechanism behind Python Decorators (which you'll build in Module 8!).
4. Interactive Trace: Closure with nonlocal Counter
Watch how make_counter() creates an independent private counter without using any global variables:
Quick Quiz: Module 5.2 — Scope & Closures
Keep Exploring: Related Lessons & Tools
All Courses →Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.
Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.