Module 17 · Advanced Python Concepts — topic 8 of 14
Closures
Functions that remember the variables of the scope they were created in: nested functions, captured variables, nonlocal for updating them, inspecting __closure__, the late-binding trap in loops, and closures as lightweight objects.
Learning objectives
- Create closures that capture variables
- Update captured variables with nonlocal
- Avoid the late-binding trap
Definition
A closure is an inner function that keeps access to variables from its enclosing function's scope even after that outer function has returned. The captured variables live on in the closure's cells.
Introduction
A function factory like make_counter() returns a new counter each time, and each one remembers its own count. That memory is a closure.
Why it matters
Closures power decorators, callbacks and small stateful helpers without writing a whole class.
Detailed explanation
A function defined inside another function can read the outer function's local variables.
If the inner function is returned or stored, it keeps those variables alive: this combination of function and captured environment is a closure.
Reading a captured variable needs nothing special. To assign to it, declare it nonlocal inside the inner function; otherwise Python creates a new local variable.
Each call of the outer function creates a fresh set of variables, so every closure it returns has independent state.
func.__closure__ holds cell objects; cell.cell_contents shows the captured values.
Closures capture variables, not values. Lambdas created in a loop all see the loop variable's final value — bind the current value with a default argument (lambda i=i: i).
A closure is like a tiny object with one method. When you need several methods or a lot of state, a class is clearer.
Syntax
- Inner functions capture outer variables.
- nonlocal allows assignment.
- Each outer call gives independent state.
Code examples
Independent counters
1 2 3 1
Inspecting a closure
Hi, Asha! Hi
More examples
Late binding and a memoising closure
[2, 2, 2] [0, 1, 2] 12586269025 51
Step-by-step explanation
- All three lambdas in the first list look up i when called, after the loop has finished, so they all return 2.
- The default argument i=i stores each value at creation time.
- memoize's wrapper closes over cache, so results survive between calls and fib(50) needs only 51 computations.
Expected output
Running “Late binding and a memoising closure” prints exactly:
Practical applications
- Callbacks configured with a value, such as a button handler for one item.
- Caching and rate-limiting helpers.
Best practices
- Use closures for small amounts of private state.
- Bind loop values with default arguments.
- Switch to a class when state grows.
Common mistakes
Assigning without nonlocal
Avoid
Prefer
Assignment makes count local unless declared nonlocal.
Important notes
- functools.lru_cache provides memoisation without writing your own closure.
Key takeaways
- Closures remember enclosing variables.
- nonlocal lets inner functions assign to them.
- Closures capture variables, not values.
Try it yourself
- 1Write make_accumulator(start) whose function adds its argument to a running total.
- 2Create button callbacks in a loop that each print their own label correctly.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
2 questions test this exact topic. Answers and explanations are revealed after you submit.
- AdvancedWhat is printed?
- AdvancedWhat is printed?