Skip to main content
Albero Academy

Closures

Functions that remember the variables from where they were created.

Functions9 min

In Python, functions are first-class — you can define one inside another and return it. A closure is such an inner function thatremembers the variables from the scope where it was created, even after that outer scope has finished running.

A function factory

The outer function's parameter is "baked into" each returned inner function:

closures capture the enclosing variable
def multiplier(factor):
def multiply(n):
return n * factor # 'factor' is captured from the outer scope
return multiply
double = multiplier(2)
triple = multiplier(3)
double(10) # 20 — remembers factor=2
triple(10) # 30 — remembers factor=3

Remembering state

Closures can hold private, per-instance state without a class. Use nonlocal to modify a captured variable:

a counter closure
def make_counter():
count = 0
def increment():
nonlocal count # modify the enclosing variable
count += 1
return count
return increment
c = make_counter()
c() # 1
c() # 2 — state persists between calls

Key takeaways

  1. 01A closure is an inner function that captures variables from its enclosing scope.
  2. 02It remembers those variables even after the outer function has returned.
  3. 03Use nonlocal to modify (not just read) a captured variable.
  4. 04Closures enable function factories and private per-instance state.
  5. 05They are the mechanism behind decorators.

Finished this chapter?

Mark it complete to track your progress through Python.