Every name in Python lives in a scope, the part of the program where that name can be seen. Knowing which scope a name belongs to explains puzzling errors such as UnboundLocalError, and it leads to one of Python’s most useful tools: the closure, a function that remembers variables from the place where it was created. This lesson covers the LEGB rule, the global and nonlocal keywords, and closures.
In this lesson you will learn
- The LEGB rule: Local, Enclosing, Global, Built-in
- When you need the
globalkeyword - Why
UnboundLocalErrorhappens - Closures and the
nonlocalkeyword - The late-binding trap with lambdas in loops
You should know functions and lambda functions.
The LEGB Rule and the global Keyword
When Python meets a name, it looks for it in four places, in this order: the Local function, any Enclosing functions, the module’s Global names, and finally the Built-in names such as len and print. It uses the first match it finds.
# LEGB: Local, Enclosing, Global, Built-in
city = "Dhaka" # global
def outer():
city = "Chattogram" # enclosing (for inner)
def inner():
city = "Sylhet" # local
print("inner sees:", city)
inner()
print("outer sees:", city)
outer()
print("module sees:", city)
print("built-in len still works:", len(city))
# Reading a global is fine; assigning needs the global keyword
visitors = 0
def visit():
global visitors
visitors += 1
visit(); visit(); visit()
print("visitors =", visitors)
# Without global, assignment makes the name local for the WHOLE function
def broken():
try:
visitors += 1 # noqa: F823
except UnboundLocalError as e:
print("UnboundLocalError:", e)
broken()
Output
inner sees: Sylhet
outer sees: Chattogram
module sees: Dhaka
built-in len still works: 5
visitors = 3
UnboundLocalError: cannot access local variable 'visitors' where it is not associated with a value
- There are three different variables called
city. Each function sees the nearest one, soinnerprints Sylhet,outerprints Chattogram and the module prints Dhaka. Assigning inside a function never changes the outer variables. lenis not defined anywhere in the file, so Python finds it in the built-in scope.- A function may read a global variable freely, but to assign to it, it must say
global visitorsfirst. Thenvisitors += 1changes the module’s variable. - In
broken()there is an assignment tovisitorsand noglobal, so Python decides, before the function runs, thatvisitorsis local for the whole function. The+=then tries to read a local that has no value yet, which raisesUnboundLocalError.
Closures and nonlocal
# A closure remembers variables from the function that created it
def make_counter(start=0):
count = start
def step():
nonlocal count # change the enclosing variable
count += 1
return count
return step
tickets = make_counter()
orders = make_counter(100)
print(tickets(), tickets(), tickets())
print(orders(), orders())
print("tickets still at", tickets())
# Closures as small configurable functions
def make_vat(rate):
def add_vat(price):
return round(price * (1 + rate), 2)
return add_vat
vat15 = make_vat(0.15)
vat5 = make_vat(0.05)
print(vat15(200), vat5(200))
print("remembered:", vat15.__closure__[0].cell_contents)
# The late-binding trap in loops
late = [lambda: i for i in range(3)]
fixed = [lambda i=i: i for i in range(3)]
print("late:", [f() for f in late])
print("fixed:", [f() for f in fixed])
Output
1 2 3
101 102
tickets still at 4
230.0 210.0
remembered: 0.15
late: [2, 2, 2]
fixed: [0, 1, 2]
make_counterreturns the inner functionstep. Even aftermake_counterhas finished,stepstill remembers itscount. A function bundled with remembered variables like this is a closure.- Each call to
make_countercreates a new, separatecount, soticketsandorderscount independently. nonlocal countletsstepassign to the enclosing function’s variable. Without it,count += 1would raiseUnboundLocalError, for the same reason as before.make_vat(0.15)builds a small, ready-configured function. You can see the remembered value in__closure__, although you rarely need to.- The last example is a classic trap. Each lambda looks up
iwhen it is called, not when it is created, and by then the loop has finished withi = 2. Writinglambda i=i: icopies the current value into a default argument, which is fixed at creation time.
global or nonlocal?
| Keyword | Lets you assign to | Typical use |
|---|---|---|
| (none) | Only local names; outer names can be read | Most functions |
global x | The module-level x | Simple scripts, settings, counters |
nonlocal x | The nearest enclosing function’s x | Closures that keep state |
Common Mistakes
- Using
globalto pass data around. Functions that change globals are hard to test. Prefer parameters and return values. - Naming a variable after a built-in, such as
list = [1, 2]. The built-inlist()is then hidden in that scope. - Expecting a loop variable to be captured by value in a lambda or inner function. Use a default argument or
functools.partial. - Using
nonlocalfor a module-level name. It only works for variables of an enclosing function; useglobalfor module names.
Practice Exercises
Exercise 1. Write make_multiplier(n) that returns a function multiplying its argument by n.
Show answer
def make_multiplier(n):
def times(x):
return x * n
return times
double = make_multiplier(2)
print(double(21)) # 42
Exercise 2. Write a closure make_average() whose returned function takes a new number each call and returns the running average.
Show answer
def make_average():
total = count = 0
def add(x):
nonlocal total, count
total += x
count += 1
return total / count
return add
avg = make_average()
print(avg(10), avg(20), avg(60)) # 10.0 15.0 30.0
Frequently Asked Questions
Do if blocks and for loops create a new scope?
No. In Python only functions, classes, modules and comprehensions create scopes. A variable set inside an if or for block is still available after the block ends.
How are closures related to decorators?
A decorator is usually a function that returns a closure. The inner wrapper function remembers the original function from the enclosing scope and calls it, adding behaviour before or after.
Summary
- Python looks up names in Local, Enclosing, Global, then Built-in scope.
- Assigning inside a function makes the name local unless you declare
globalornonlocal. - A closure is an inner function that remembers variables from where it was made.
- Lambdas in loops see the variable’s final value; bind it with a default argument.
Next: Python functools Module.
