PythonMastery
Python programs · Functions · intermediate

Closure in Python

A closure is an inner function that remembers variables from the function that created it. Build a multiplier and a counter with nonlocal.

A closure is an inner function that remembers the variables of the outer function that created it, even after the outer function has finished.

The program

python
def multiplier(n):
    def multiply(x):
        return x * n
    return multiply

double = multiplier(2)
triple = multiplier(3)

print(double(5))
print(triple(5))
print(double(10))
output
10
15
20

How it works

A counter with nonlocal

An inner function can read the outer variable without any extra code. To change it, declare it nonlocal first. Without that line, count += 1 raises an UnboundLocalError:

python
def make_counter():
    count = 0

    def increment():
        nonlocal count
        count += 1
        return count

    return increment

counter = make_counter()
print(counter())
print(counter())
print(counter())

other = make_counter()
print(other())
output
1
2
3
1

counter and other each have their own count. Closures are the idea behind decorators, which wrap a function inside another function in the same way.

Learn the idea: Functions & Scoping, Decorators: Functions That Wrap Functions