ZetCode

Python closures

last modified November 18, 2026 Python 3.15

In this article we show how to use closures in Python.

Python functions are first-class objects. They can be assigned to variables, stored in collections, created at runtime, passed as arguments, and returned from other functions. Closures build on this: a function created inside another function can remember the variables of the scope in which it was created.

Nested functions

A nested function, also called an inner function, is a function defined inside another function. It is created each time the outer function runs and is visible only inside it.

nested_fun.py
def greet_all(names):

    def build_message(name):
        return f'Hello {name}!'

    for name in names:
        print(build_message(name))


greet_all(['Peter', 'Lucia', 'Martin'])

try:
    build_message('Jane')
except NameError as e:
    print(e)

The build_message function is defined and called inside the greet_all function. Outside of it, the name does not exist, so the call at module level raises NameError.

$ python nested_fun.py
Hello Peter!
Hello Lucia!
Hello Martin!
name 'build_message' is not defined

Closures

A closure is a nested function that refers to variables of an enclosing function and keeps access to them after the enclosing function has returned. Such variables are called free variables: they are used in the inner function but not defined there.

A closure is formed when:

Closures let us attach state to a function without global variables or a class. They are the mechanism behind function factories, callbacks, and decorators.

A simple closure

The following is a simple example of a closure.

simple_closure.py
def make_printer(msg):

    def printer():
        print(msg)

    return printer


hello = make_printer('Hello there')
bye = make_printer('Good bye')

hello()
hello()
bye()

The make_printer function creates and returns a printer function. The printer function is the closure; msg is its free variable.

hello = make_printer('Hello there')
bye = make_printer('Good bye')

Each call to make_printer creates a new printer function with its own msg. When make_printer returns, its local scope is gone, but the returned function still has access to the value it was created with.

$ python simple_closure.py
Hello there
Hello there
Good bye

Inspecting a closure

The free variables are stored in cells. The names are listed in the co_freevars attribute of the function's code object, and the cells are in the __closure__ attribute. The value of a cell is available in its cell_contents attribute.

inspect_closure.py
def make_greeter(greeting, punct):

    def greeter(name):
        return f'{greeting} {name}{punct}'

    return greeter


greet = make_greeter('Hello', '!')
print(greet('Peter'))

print(greet.__code__.co_freevars)
print(greet.__closure__)

for name, cell in zip(greet.__code__.co_freevars, greet.__closure__):
    print(name, '=', repr(cell.cell_contents))

print(make_greeter.__closure__)

We create a greeter closure with two free variables and look inside it.

for name, cell in zip(greet.__code__.co_freevars, greet.__closure__):
    print(name, '=', repr(cell.cell_contents))

The names and the cells are in the same order, so we can pair them with zip.

print(make_greeter.__closure__)

A function with no free variables, such as the module-level make_greeter, has __closure__ set to None. The memory addresses in the output differ from run to run.

$ python inspect_closure.py
Hello Peter!
('greeting', 'punct')
(<cell at 0x7f41ac5edd80: str object at 0x7f41ac5ed6b0>, <cell at 0x7f41ac5edde0: str object at 0x1534ab8>)
greeting = 'Hello'
punct = '!'
None

The nonlocal keyword

A closure can read a free variable without any declaration. To assign to it, the variable must be declared with the nonlocal keyword; otherwise the assignment creates a new local variable of the inner function.

counter.py
def make_counter():

    count = 0

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

    return counter


c1 = make_counter()
c2 = make_counter()

print(c1(), c1(), c1())
print(c2(), c2())
print(c1())

The example creates two independent counters.

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

The nonlocal declaration makes count refer to the variable of make_counter, so count += 1 updates the value stored in the cell.

c1 = make_counter()
c2 = make_counter()

Every call to make_counter creates a new count variable, so the two counters do not share their state.

$ python counter.py
1 2 3
1 2
4

Assignment without nonlocal

If we forget the nonlocal declaration, the compiler treats count as a local variable of the inner function, because it is assigned to there.

no_nonlocal.py
def make_counter():

    count = 0

    def counter():
        count += 1
        return count

    return counter


counter = make_counter()

try:
    counter()
except UnboundLocalError as e:
    print(f'{type(e).__name__}: {e}')

The augmented assignment count += 1 reads count before it has been assigned in the local scope, which raises UnboundLocalError.

Mutating an object does not need nonlocal: calling data.append(val) on a list from the enclosing scope only reads the variable data. Only rebinding the name requires the declaration.

$ python no_nonlocal.py
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value

Function factories

A function that builds and returns configured functions is called a function factory. Closures make such factories short.

multipliers.py
def make_multiplier(n):

    def multiply(x):
        return x * n

    return multiply


double = make_multiplier(2)
triple = make_multiplier(3)

print(double(7), triple(7))

vals = [1, 2, 3, 4, 5]
print(list(map(triple, vals)))

power = lambda e: lambda x: x ** e
square, cube = power(2), power(3)
print(square(5), cube(5))

The make_multiplier factory returns functions that multiply their argument by a fixed number.

print(list(map(triple, vals)))

The created closures are ordinary functions and can be passed to map, sorted, and other higher-order functions.

power = lambda e: lambda x: x ** e

Lambdas can form closures too. The outer lambda returns an inner lambda that remembers the exponent e.

$ python multipliers.py
14 21
[3, 6, 9, 12, 15]
25 125

Late binding

A closure stores a reference to the variable, not a copy of its value. The value is looked up when the closure is called. This is a common source of bugs when closures are created in a loop.

late_binding.py
funcs = []

for i in range(3):
    funcs.append(lambda: i)

print([f() for f in funcs])

fixed = []

for i in range(3):
    fixed.append(lambda i=i: i)

print([f() for f in fixed])


def make_fun(i):
    return lambda: i


made = [make_fun(i) for i in range(3)]
print([f() for f in made])

We create three lambdas in a loop in three different ways.

for i in range(3):
    funcs.append(lambda: i)

All three lambdas refer to the same variable i. When they are called after the loop, i is 2, so every lambda returns 2.

for i in range(3):
    fixed.append(lambda i=i: i)

A default argument value is evaluated when the function is defined, so each lambda captures the current value of i.

def make_fun(i):
    return lambda: i

Calling a factory function creates a new scope for every value, which is the cleaner fix.

$ python late_binding.py
[2, 2, 2]
[0, 1, 2]
[0, 1, 2]

A class with __call__

A small class with the __call__ method is an alternative to a closure. Its instances can be called like functions and keep their state in attributes.

summer_class.py
class Summer:

    def __init__(self):
        self.data = []

    def __call__(self, val):
        self.data.append(val)
        return sum(self.data)


summer = Summer()

print(summer(1))
print(summer(2))
print(summer(3))
print(summer(4))

The Summer class sums the values passed to the object.

def __init__(self):
    self.data = []

The data is kept in an instance attribute created in the constructor.

def __call__(self, val):
    self.data.append(val)
    return sum(self.data)

Each time the instance is called, the value is appended and the sum is returned.

$ python summer_class.py
1
3
6
10

The same with a closure

The following is an equivalent solution with a closure.

summer_closure.py
def make_summer():

    data = []

    def summer(val):
        data.append(val)
        return sum(data)

    return summer


summer = make_summer()

print(summer(1))
print(summer(2))
print(summer(3))
print(summer(4))

The list lives in the enclosing scope of summer. Because we only mutate the list and never rebind data, no nonlocal declaration is needed.

A closure is lighter for a single operation; a class is clearer when the state needs several methods, a readable repr, or inheritance.

$ python summer_closure.py
1
3
6
10

Several functions sharing state

Functions are objects and can have attributes. We can attach a second closure to the first one so that both share the same free variables.

running_avg.py
def make_averager():

    total = 0
    count = 0

    def averager(val):
        nonlocal total, count
        total += val
        count += 1
        return total / count

    def reset():
        nonlocal total, count
        total = count = 0

    averager.reset = reset
    return averager


avg = make_averager()

for temp in [12.5, 14.0, 13.5, 16.0]:
    print(f'{avg(temp):.2f}')

avg.reset()
print(avg(20))

The example computes a running average of temperatures and can reset it.

def averager(val):
    nonlocal total, count
    ...

A single nonlocal statement can list several names.

averager.reset = reset
return averager

Both averager and reset close over the same total and count cells, so resetting affects the next average.

$ python running_avg.py
12.50
13.25
13.33
14.00
20.0

Closures in decorators

A decorator is a function that takes a function and returns a replacement for it. The replacement is usually a closure over the original function and any extra state.

memoize.py
def memoize(fn):

    cache = {}

    def wrapper(n):
        if n not in cache:
            cache[n] = fn(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(80))
print(len(fib.cache))

The memoize decorator caches the results of a one-argument function.

def wrapper(n):
    if n not in cache:
        cache[n] = fn(n)
    return cache[n]

The wrapper closure has two free variables: the decorated function fn and the cache dictionary. The recursive calls inside fib go through the wrapper too, so each Fibonacci number is computed only once.

In real code, the standard functools.cache decorator does the same job.

$ python memoize.py
23416728348467685
81

Decorator with mutable state

The next decorator counts the calls of a function. The counter is an integer, so the wrapper needs nonlocal to update it.

call_counter.py
import functools


def count_calls(fn):

    calls = 0

    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        nonlocal calls
        calls += 1
        print(f'{fn.__name__} call #{calls}')
        return fn(*args, **kwargs)

    return wrapper


@count_calls
def add(a, b):
    return a + b


print(add(1, 2))
print(add(3, 4))
print(add.__name__)

Every call of add increments and prints the counter before calling the original function.

@functools.wraps(fn)
def wrapper(*args, **kwargs):

The functools.wraps decorator copies the name, docstring, and other metadata of the original function to the wrapper, so add.__name__ is still add.

$ python call_counter.py
add call #1
3
add call #2
7
add

Closures and functools.partial

When a closure only fixes some arguments of an existing function, the functools.partial function is a ready-made alternative.

partial_vs_closure.py
from functools import partial


def log(level, msg):
    print(f'[{level}] {msg}')


def make_logger(level):

    def logger(msg):
        log(level, msg)

    return logger


warn = make_logger('WARN')
info = partial(log, 'INFO')

warn('disk almost full')
info('backup finished')

print(info.func.__name__, info.args)
print(warn.__closure__[0].cell_contents)

We create a logger for the WARN level with a closure and a logger for the INFO level with partial.

print(info.func.__name__, info.args)
print(warn.__closure__[0].cell_contents)

A partial object exposes the wrapped function and the fixed arguments as attributes; the closure keeps the level in a cell.

$ python partial_vs_closure.py
[WARN] disk almost full
[INFO] backup finished
log ('INFO',)
WARN

Source

Naming and binding – Python language reference

The nonlocal statement

In this article we have worked with closures in Python. See also Python decorators, Python lambda functions, and Python functions.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.