Closures & Lexical Scope
Published by Brayan K
Once you master closures, you unlock the ability to create custom function factories, stateful functions, decorators, event handlers, configuration-based logic, and real-world abstractions used in production systems.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
A function looks names up where it was written
Higher-Order Functions & Function Factories made functions inside functions and returned them. This lesson is about how those inner functions find the names they use. The rule is called lexical scope: a function looks a name up in the code around it where it was written, not around the line that calls it.
def make_greeter(greeting):
def greet(name):
return f"{greeting}, {name}!"
return greet
def welcome_desk(name):
greeting = "Welcome"
return hello(name)
hello = make_greeter("Hello")
greeting = "Hey"
print(welcome_desk("Ada"))
print(hello("Ada"))
# ✅ Expected output:
# Hello, Ada!
# Hello, Ada!welcome_desk has a greeting of its own, and so does the module, but greet was written inside make_greeter, so it uses that function's greeting. Python searches in a fixed order: the function's own names, then the functions it's written inside, then the module, then the built-in names. Scope: global, nonlocal & LEGB covers that order in full. It only goes outwards: the outer function can't see the inner function's names, as Functions showed for any function.
def make_greeter(greeting):
def greet(name):
message = f"{greeting}, {name}!"
return message
greet("Ada")
return message
make_greeter("Hello")
# ✅ Expected error:
# NameError: name 'message' is not definedThe inner function keeps the variables it uses
When make_multiplier returns, its variable factor would normally be gone. But multiply uses it, so Python keeps it for multiply, separately for each call:
def make_multiplier(factor):
def multiply(x):
return x * factor
return multiply
times_3 = make_multiplier(3)
times_10 = make_multiplier(10)
print(times_3(5), times_10(5))
print(times_3(7), times_10(7))
# ✅ Expected output:
# 15 50
# 21 70A function together with the variables it keeps from the functions around it is a closure. You can look inside: __code__.co_freevars names the kept variables, and __closure__ holds one cell per variable, whose cell_contents is the value:
def make_multiplier(factor):
def multiply(x):
return x * factor
return multiply
times_3 = make_multiplier(3)
times_10 = make_multiplier(10)
print(times_3.__code__.co_freevars)
print(times_3.__closure__[0].cell_contents)
print(times_10.__closure__[0].cell_contents)
print(make_multiplier.__closure__)
# ✅ Expected output:
# ('factor',)
# 3
# 10
# Nonemake_multiplier itself keeps nothing, so its __closure__ is None. A closure keeps only the names it uses, not everything the outer function had:
def make_report(title, rows):
footer = "-- end --"
def render():
return f"{title}: {len(rows)} rows"
return render
report = make_report("Sales", [120, 80, 95])
print(report())
print(report.__code__.co_freevars)
# ✅ Expected output:
# Sales: 3 rows
# ('rows', 'title')footer isn't kept. (The names come out in alphabetical order here, not in the order the code uses them.)
It keeps the variable, not a copy of the value
A closure doesn't take a snapshot when the inner function is made. It keeps the variable itself, and reads it each time it runs, so a later change shows:
def make_greeter():
greeting = "Hello"
def greet(name):
return f"{greeting}, {name}!"
greeting = "Welcome"
return greet
greet = make_greeter()
print(greet("Ada"))
# ✅ Expected output:
# Welcome, Ada!Two inner functions made by the same call share one variable, while another call gets a variable of its own. Here add and show share a list:
def make_tally():
marks = []
def add(mark):
marks.append(mark)
def show():
return " ".join(marks)
return add, show
add_a, show_a = make_tally()
add_b, show_b = make_tally()
add_a("x")
add_a("y")
add_b("z")
print(show_a())
print(show_b())
# ✅ Expected output:
# x y
# zChanging a kept variable needs nonlocal
Reading a kept variable is free, but assigning to one isn't what it looks like. An assignment inside a function makes a new local variable of that function, so this setter changes nothing, silently:
def make_greeter():
greeting = "Hello"
def set_greeting(new):
greeting = new
def greet(name):
return f"{greeting}, {name}!"
return set_greeting, greet
set_greeting, greet = make_greeter()
set_greeting("Hi")
print(greet("Ada"))
# ✅ Expected output:
# Hello, Ada!A counter fails loudly instead: clicks += 1 assigns to clicks, so clicks is a local of click, and += reads that local before it has a value. The error is an UnboundLocalError, whose message is worded differently in Python 3.10 than in later versions, so this example prints only the error's name:
def make_counter():
clicks = 0
def click():
clicks += 1
return clicks
return click
tally = make_counter()
try:
tally()
except NameError as e:
print(type(e).__name__)
# ✅ Expected output:
# UnboundLocalErrorexcept NameError catches it because UnboundLocalError is a kind of NameError, as Inheritance and Polymorphism showed for error families. nonlocal clicks tells Python that clicks means the enclosing function's variable:
def make_counter():
clicks = 0
def click():
nonlocal clicks
clicks += 1
return clicks
return click
likes = make_counter()
shares = make_counter()
print(likes(), likes(), likes())
print(shares())
# ✅ Expected output:
# 1 2 3
# 1Changing an object a variable refers to isn't assigning to the variable, so append() on a kept list needs no nonlocal. lines += [text] does assign, though, and fails like the counter without it.
def make_log():
lines = []
def log(text):
lines.append(text)
return len(lines)
return log
log = make_log()
log("start")
print(log("stop"))
# ✅ Expected output:
# 2nonlocal only reaches a variable of an enclosing function. Pointed at a variable at the top of the file, it's refused before anything in the file runs, so even the print at the end never happens:
total = 0
def make_adder():
def add(n):
nonlocal total
total += n
return total
return add
print("this line never runs")
# ✅ Expected error:
# SyntaxError: no binding for nonlocal 'total' foundFor variables at the top of a file, the keyword is global, which Scope: global, nonlocal & LEGB covers.
Functions made in a loop share the loop's variable
Lambda Functions warned that lambdas made in a loop all see the loop variable's last value. Here is why:
multipliers = []
for size in [1, 2, 3]:
multipliers.append(lambda n: n * size)
print([m(10) for m in multipliers])
size = 100
print([m(10) for m in multipliers])
# ✅ Expected output:
# [30, 30, 30]
# [1000, 1000, 1000]Each lambda looks size up when it's called, not when it's made. By then the loop has finished, and Loops showed that the loop variable keeps its last value, 3; change it, and every result changes. It isn't about lambda: functions defined with def in a loop do the same, which is a real bug when each one handles a button:
buttons = {}
for label in ["Save", "Open", "Quit"]:
def on_click():
return f"{label} clicked"
buttons[label] = on_click
print(buttons["Save"]())
print(buttons["Open"]())
# ✅ Expected output:
# Quit clicked
# Quit clickedThe first fix is a default argument. A default is worked out once, when the def line runs, so each function stores the label of its own pass through the loop:
buttons = {}
for label in ["Save", "Open", "Quit"]:
def on_click(label=label):
return f"{label} clicked"
buttons[label] = on_click
print(buttons["Save"]())
print(buttons["Open"]())
print(buttons["Save"].__defaults__)
# ✅ Expected output:
# Save clicked
# Open clicked
# ('Save',)It isn't a copy: the default is the same object the loop variable referred to. And a caller can replace it by passing an argument, which nobody meant to allow:
buttons = {}
for label in ["Save", "Open", "Quit"]:
def on_click(label=label):
return f"{label} clicked"
buttons[label] = on_click
print(buttons["Save"]("Delete"))
# ✅ Expected output:
# Delete clickedThe cleaner fix is a factory, as in Higher-Order Functions & Function Factories: each call of make_handler makes a new label variable for its function to keep.
def make_handler(label):
def on_click():
return f"{label} clicked"
return on_click
buttons = {}
for label in ["Save", "Open", "Quit"]:
buttons[label] = make_handler(label)
print(buttons["Save"]())
print(buttons["Open"]())
# ✅ Expected output:
# Save clicked
# Open clickedA comprehension behaves the same way: [lambda n: n * size for size in [1, 2, 3]] makes three lambdas that share one size. functools.partial is a third fix, which functools: lru_cache, partial, reduce covers.
Closures, classes and default arguments all keep state
A function that remembers something between calls can be built three ways, and they don't keep it in the same place:
def make_counter():
clicks = 0
def click():
nonlocal clicks
clicks += 1
return clicks
return click
class Counter:
def __init__(self):
self.clicks = 0
def click(self):
self.clicks += 1
return self.clicks
def click_once_more(_clicks=[0]):
_clicks[0] += 1
return _clicks[0]
a, b = make_counter(), make_counter()
print(a(), a(), b())
c, d = Counter(), Counter()
print(c.click(), c.click(), d.click(), c.clicks)
print(click_once_more(), click_once_more(), click_once_more())
# ✅ Expected output:
# 1 2 1
# 1 2 1 2
# 1 2 3- The closure keeps one count per make_counter() call, reachable only through the function. It suits one job with a little state.
- The class keeps one count per object, and other code can read c.clicks or call a reset() method. Once several functions share state and others need to read it, a class from Object-Oriented Programming is clearer.
- The default argument keeps one count for the whole program, made when the def ran: the trap Advanced Functions & Parameters Masterclass showed, used on purpose.
Four jobs for closures: rules, IDs, limits and events
Checks built from configuration: each rule is a closure keeping its own limits, made from a table rather than written out by hand.
def between(low, high):
def check(value):
return low <= value <= high
return check
rules = {"age": between(18, 120), "rating": between(1, 5)}
form = {"age": 17, "rating": 4}
for field, check in rules.items():
print(field, "ok" if check(form[field]) else "out of range")
# ✅ Expected output:
# age out of range
# rating okNumbered IDs, each series counting on its own. 04d pads the number with zeros to four digits, as f-strings & String Formatting showed:
def make_id_maker(prefix):
last = 0
def next_id():
nonlocal last
last += 1
return f"{prefix}-{last:04d}"
return next_id
invoice_id = make_id_maker("INV")
refund_id = make_id_maker("REF")
print(invoice_id(), invoice_id(), refund_id(), invoice_id())
# ✅ Expected output:
# INV-0001 INV-0002 REF-0001 INV-0003A limit on how often something can happen, wrapped around any function:
def limit_calls(func, max_calls):
calls = 0
def wrapper(*args):
nonlocal calls
if calls >= max_calls:
return "limit reached"
calls += 1
return func(*args)
return wrapper
def send(to):
return f"sent to {to}"
send_3 = limit_calls(send, 3)
for to in ["ana", "ben", "cy", "dee"]:
print(send_3(to))
# ✅ Expected output:
# sent to ana
# sent to ben
# sent to cy
# limit reachedEvent handlers: two functions sharing one dictionary of handlers, so code can register what should happen when an event occurs, and fire it later.
def make_event_bus():
handlers = {}
def on(event, handler):
if event not in handlers:
handlers[event] = []
handlers[event].append(handler)
def emit(event, data):
return [handler(data) for handler in handlers.get(event, [])]
return on, emit
on, emit = make_event_bus()
on("signup", lambda user: f"welcome email to {user}")
on("signup", lambda user: f"log: {user} joined")
print(emit("signup", "ada"))
print(emit("logout", "ada"))
# ✅ Expected output:
# ['welcome email to ada', 'log: ada joined']
# []Decorators are closures too
limit_calls above took a function and returned a wrapper that keeps it. That's the shape of a decorator: the wrapper is a closure over the function it was given.
def shout(func):
def wrapper():
return func().upper()
return wrapper
def greet():
return "hi"
loud = shout(greet)
print(loud())
print(loud.__code__.co_freevars)
print(loud.__closure__[0].cell_contents is greet)
# ✅ Expected output:
# HI
# ('func',)
# TrueDecorators & Advanced Features covers the @ line that applies a function like shout to a def, and the details a wrapper should copy from the function it wraps.
Practice: buttons that count their own clicks
Each button should count its own presses. Fill the three blanks: the keyword that lets press change clicks, what the factory returns, and what the loop passes to it. The hints below the code go in the blanks from the top.
def make_button(label):
clicks = 0
def press():
___ clicks
clicks += 1
return f"{label}: {clicks}"
return ___
buttons = {}
for label in ["Save", "Open"]:
buttons[label] = make_button(___)
print(buttons["Save"]())
print(buttons["Save"]())
print(buttons["Open"]())
# 👉 replace ___ with nonlocal
# 👉 replace ___ with press
# 👉 replace ___ with label
# ✅ Expected output:
# Save: 1
# Save: 2
# Open: 1With return press() in the second blank, the factory presses the button once and returns the text, so calling it fails with TypeError: 'str' object is not callable.
On your own: a running average
Write make_averager(). It keeps a running total and a count as two plain numbers, not a list, and returns a function add(value) that returns the average so far, rounded to 2 decimal places.
Make one averager and print the results of adding 10, 20, 30 and 0, then show that a new averager starts fresh by printing make_averager()(5). If the first call stops with an UnboundLocalError, the inner function is missing a nonlocal line; one line can name both variables.
# Write make_averager() here.
# your code heredef make_averager():
total = 0
n = 0
def add(value):
nonlocal total, n
total += value
n += 1
return round(total / n, 2)
return add
avg = make_averager()
print(avg(10))
print(avg(20))
print(avg(30))
print(avg(0))
print(make_averager()(5))
# ✅ Expected output:
# 10.0
# 15.0
# 20.0
# 15.0
# 5.0
Practice quiz
make_label() sets text = "draft", defines def show(): return text, then sets text = "final" and returns show. What does print(make_label()()) show?
- draft
- final
- None
- It stops with NameError: name 'text' is not defined
Answer: final. show keeps the variable text, not the value it had when show was defined, and reads it when called.
hello = make_greeter("Hello") returns a greet(name) that uses greeting. welcome_desk(name) sets its own greeting = "Welcome" and returns hello(name). What does print(welcome_desk("Ada")) show?
- Welcome, Ada!
- It stops with NameError: name 'greeting' is not defined
- None
- Hello, Ada!
Answer: Hello, Ada!. greet looks names up where it was written, inside make_greeter, not where it's called.
make_counter() sets clicks = 0 and returns def click(): clicks += 1; return clicks, with no nonlocal. What does tally = make_counter(), then print(tally()) do?
- 1
- 0
- It stops with an UnboundLocalError
- None
Answer: It stops with an UnboundLocalError. Assigning to clicks makes it a local of click, and += reads that local before it has a value.
make_greeter() sets greeting = "Hello" and returns set_greeting(new), which runs greeting = new with no nonlocal, and greet(name). After set_greeting("Hi"), what does print(greet("Linus")) show?
- Hi, Linus!
- It stops with an UnboundLocalError
- None
- Hello, Linus!
Answer: Hello, Linus!. greeting = new made a new local in set_greeting and changed nothing. nonlocal greeting would have changed the shared one.
A loop over ["Save", "Open", "Quit"] defines def on_click(): return f"{label} clicked" and stores it in buttons[label]. What does print(buttons["Save"]()) show?
- Quit clicked
- Save clicked
- Open clicked
- It stops with NameError: name 'label' is not defined
Answer: Quit clicked. Every on_click looks label up when it's called, and after the loop label is "Quit".
for n in [1, 2, 3]: fs.append(lambda n=n: n * 10). What does print([f() for f in fs]) show?
- [30, 30, 30]
- [10, 20, 30]
- [10, 10, 10]
- It stops with a TypeError
Answer: [10, 20, 30]. n=n gives each lambda a default worked out when that lambda was made: 1, 2, then 3.
make_adder(n) defines def add(x): return x + n but has no return line. What does add_2 = make_adder(2), then print(add_2(5)) do?
- It stops with TypeError: 'NoneType' object is not callable
- 7
- None
- It stops with NameError: name 'add' is not defined
Answer: It stops with TypeError: 'NoneType' object is not callable. Without return add, make_adder gives None, and None can't be called.
make_counter() keeps clicks with nonlocal and returns the new count. a = make_counter(), b = make_counter(), then a() and a(). What does print(a(), b()) show?
- 3 4
- 1 1
- 3 1
- 2 1
Answer: 3 1. Each make_counter() call makes its own clicks variable: a reaches 3, and b's first call gives 1.
Continue this course
- Previous: Higher-Order Functions & Function Factories
- Next: Context Managers & the with Statement in Depth — Write custom context managers for resource and lifecycle control
- Quick reference: Python cheat sheet
Frequently asked questions
Is every lambda a closure?
Only when it uses a variable of a function it was made in. A lambda written at the top of a file has no closure (its __closure__ is None) and reads module-level names when it runs; the lambda that make_adder(2) returns keeps one cell, for n.
How can I see what a closure has kept?
inspect.getclosurevars(fn).nonlocals gives a dictionary of the kept names and their values, such as {'factor': 3}. Introspection with inspect covers that module.
Can code outside the function change a kept variable?
Not by name, but nothing stops it: a cell's cell_contents can be assigned, so tally.__closure__[0].cell_contents = 100 makes the next tally() return 101. Python has no truly private state; that's for debugging, not for programs.
Is functools.partial a closure?
No. partial(multiply, factor=3) returns a partial object, which stores the function and the filled-in arguments itself: it has no __closure__ at all, though calling it works like a closure would.
What about functions nested two deep?
Reading works through every level: an inner function inside a middle one can use the outer function's variable. nonlocal changes the nearest enclosing function that has the name, so if the middle function has its own variable of that name, that's the one it changes.