Python Master Course V2 — 105. Closures and Lexical Scope
SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 11 · LESSON 105 OF 200
Closures and Lexical Scope
Study: 90–120 minutes · Prerequisites: Lessons 101–102, functions, classes, exceptions and tests.
Video lesson
Video not yet available. A verified video URL/player will be added when supplied.
Learning outcomes
Explain closures and lexical scope, reason about runtime behavior, apply the technique in a maintainable program, and test normal, boundary and invalid inputs.
Understand and apply: Closures and Lexical Scope
Closures retain references to bindings in enclosing scopes. nonlocal allows rebinding an enclosing variable; separate closure instances can keep independent state.
A closure retains a binding from an enclosing function
Python resolves ordinary function names by searching local, enclosing function, global and built-in scopes, often summarized as LEGB. A nested function can refer to an enclosing function’s variables. When the nested function escapes as a returned value, those referenced bindings remain available even after the outer call has finished. That combination of function and retained environment is a closure.
A closure captures access to a binding, not necessarily a frozen copy of its current value. This makes closures useful for configurable predicates, callbacks and small stateful functions. A factory called twice creates two enclosing environments. Functions returned by the same call can share one environment, which allows advance, read and reset operations to cooperate without using global variables.
Python example
def make_counter(start=0):
if type(start) is not int or start < 0:
raise ValueError("start must be a nonnegative integer")
count = start
def advance(step=1):
nonlocal count
if type(step) is not int or step <= 0:
raise ValueError("step must be a positive integer")
count += step
return count
def read():
return count
def reset():
nonlocal count
count = start
return advance, read, reset
advance_a, read_a, reset_a = make_counter(10)
advance_b, read_b, reset_b = make_counter()
print(advance_a(), advance_a(3), advance_b())
reset_a()
print(read_a(), read_b())
try:
advance_a(0)
except ValueError:
print("invalid step rejected")
print(read_a())
Expected output
11 14 1
10 1
invalid step rejected
10
Assignment normally makes a name local throughout that function body. Without nonlocal, count += step would try to read a not-yet-assigned local count and raise UnboundLocalError. nonlocal directs rebinding to an existing enclosing function binding. read needs no declaration because it never rebinds count. reset changes the same count that advance and read access, while the second factory call remains independent.
Separate rebinding from mutation
Appending to an enclosing list changes the existing object; it does not assign a new object to the enclosing name. Therefore items.append(value) needs no nonlocal declaration. Writing items = [] does rebind a name and requires nonlocal when the enclosing variable should change. A closure over a mutable object still sees other references mutate that object. Returning a tuple snapshot can prevent callers from modifying a private list directly.
Understand late binding in callback loops
Python example
def make_callbacks():
callbacks = []
for index in range(3):
callbacks.append(lambda: index)
return callbacks
late = make_callbacks()
early = [lambda index=index: index for index in range(3)]
print([callback() for callback in late])
print([callback() for callback in early])
Expected output
[2, 2, 2]
[0, 1, 2]
All late callbacks read the same enclosing index when they are eventually called; the loop has left that binding at two. In the second version, each default argument is evaluated when its lambda is created, so each function keeps its own current value. A small factory such as make_callback(index) is another readable solution when callbacks need several captured values.
Default arguments retain object references too. Capturing a list with a default does not create an immutable deep snapshot. For complex state, a class with explicit attributes may make ownership and debugging clearer. Neither nonlocal nor a closure automatically provides thread safety; concurrent increments require a separate synchronization design.
For the request-counter project, verify initial state, multiple increments, reset to the configured starting value, independence between factories and unchanged state after a rejected step. These tests describe observable behavior rather than relying on implementation details such as a function’s __closure__ cells. The same retained-environment mechanism explains how a decorator wrapper remembers its original callable.
Progressive runnable examples
Requires Python 3.10+. Save as lesson105.py and run python lesson105.py or python3 lesson105.py. Expected outputs below are illustrative and not claimed to have been executed on Smartyfy.
This compact warm-up returns one increment function. The expanded project above returns three cooperating operations: advance, read and reset.
Example 1 — Core mechanism
def make_counter():
count = 0
def advance():
nonlocal count
count += 1
return count
return advance
first = make_counter()
second = make_counter()
print(first(), first(), second())
Expected output:
1 2 1
Guided practical project
Project: Build independent request counters with reset behavior and tests for state isolation.
Use the complete implementation and explicit contract in the worked explanation above. Reproduce its deterministic sample, test the stated boundary and failure cases, and explain the documented limitations before adapting it.
Common mistakes and debugging
- Adding abstraction without a demonstrated need.
- Hiding state or unexpected side effects.
- Assuming type hints replace validation.
- Ignoring resource cleanup or error propagation.
- Measuring performance on unrepresentative data.
- Failing to test boundary and error cases.
Debug by reproducing the smallest failing input, inspecting the traceback and intermediate values, then adding a regression test.
Practice with explained answers
Predict each result before opening the answer. Trace state changes and explain the contract as well as the output.
Why does count += step require nonlocal?
Augmented assignment both reads and rebinds count. Without nonlocal, Python treats count as local to advance, so the initial read occurs before a local value exists. nonlocal connects that assignment to the count created by make_counter.
Why does read() need no nonlocal declaration?
It only reads count, so normal enclosing-scope lookup finds the binding. nonlocal is needed when assigning to an enclosing function variable, not whenever a nested function mentions one.
After reset_a(), why is read_b() still one?
Each make_counter call created a different enclosing environment. The three A operations share one count, and the three B operations share another. Resetting A changes no B binding.
Why do the late-bound callbacks all return two?
The functions are called after the loop finishes, and each reads the same index binding at that later time. A default parameter evaluates its value at creation, which gives the early-bound callbacks separate zero, one and two defaults.
Does an enclosing list need nonlocal for append or clear?
No. Both mutate the existing list object. Assigning items = [] is different: it binds a new list to a name. Use nonlocal for that enclosing-name replacement, or deliberately mutate the existing object if shared references should observe the change.
How should the counter test a rejected increment?
Record the value, call advance with an invalid step, assert ValueError, and confirm the original value remains unchanged. Validation must occur before count is updated.
Worked answer: continue after the expanded make_counter definition
advance, read, reset = make_counter(4)
try:
advance(True)
except ValueError:
pass
else:
raise AssertionError("bool accepted as a step")
assert read() == 4
Mastery checkpoint
Explain the concept without notes, reproduce the core example, finish the project, run three tests and justify when the technique is appropriate. No account-synced completion or certification is claimed.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.