Python · Module 05: Functions & ScopeTutorial 14 of 30
All Tutorials·~1.5 hrs

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).

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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!

Visual: The LEGB Scope Rule — How Python Looks Up Any Variable Name (Inside → Out)
4. B — Built-in (len, print, sum, int, range)3. G — Global (Top-level variables in your .py file)2. E — Enclosing (Outer function's variables — used by Closures!)1. L — Local (Variables inside the CURRENT function — Checked FIRST!)Not found in L → check E → check G → check B → else NameError!
PYTHON
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!

PYTHON
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!

PYTHON
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:

Tracing a Closure Counter Using nonlocal
Interactive Line-by-Line Execution Trace · Step 1 of 4
1def make_counter():
2 count = 0
3 def step():
4 nonlocal count
5 count += 1
6 return count
7 return step
8→c = make_counter()
9print(c(), c())
Variables in Memory
count (enclosing)0int
c<closure step>func
Console Output
(nothing printed yet)
What just happened: make_counter() creates count = 0 and returns the inner function 'step', which keeps a hidden link to count.

Quick Quiz: Module 5.2 — Scope & Closures

Q1.What does LEGB stand for in Python's variable lookup order?
Q2.Which keyword allows an inner function to modify a variable defined in its outer enclosing function?
Q3.What happens if you shadow a built-in by writing `len = 5` at the top of your script?

Keep Exploring: Related Lessons & Tools

All Courses →