Skip to content

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.

Beginner 10 min read·Lesson 254 of 306 in Python Programming

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

Python
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
  • Inner functions capture outer variables.
  • nonlocal allows assignment.
  • Each outer call gives independent state.

Code examples

Independent counters

Python
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
c1 = make_counter()
c2 = make_counter()
print(c1(), c1(), c1(), c2())
Output
1 2 3 1

Inspecting a closure

Python
def make_greeter(greeting):
def greet(name):
return f"{greeting}, {name}!"
return greet
hi = make_greeter("Hi")
print(hi("Asha"))
print(hi.__closure__[0].cell_contents)
Output
Hi, Asha!
Hi

More examples

Late binding and a memoising closure

Python
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs])
def memoize(func):
cache = {}
def wrapper(n):
if n not in cache:
cache[n] = func(n)
return cache[n]
wrapper.cache = cache
return wrapper
@memoize
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(50), len(fib.cache))
Output
[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:

TextOutput
[2, 2, 2]
[0, 1, 2]
12586269025 51

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

def increment():
count += 1 # UnboundLocalError

Prefer

def increment():
nonlocal count
count += 1

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

  1. 1
    Write make_accumulator(start) whose function adds its argument to a running total.
  2. 2
    Create 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?
Practise this topic