Advanced   Chapter 140 · 30 min read · Module 11: Advanced Python

Closures

Learning objectives
  • After this chapter you can explain what a closure is and when Python creates one.
  • You can write a function factory that returns customised inner functions.
  • You can use nonlocal to update an enclosing variable.
  • You can inspect captured values with __closure__.
  • You can avoid the late binding problem when creating functions in a loop.

Normally, when a function finishes, its local variables are gone. Closures are an interesting exception. An inner function can keep using variables from the outer function even after the outer function has returned. The inner function carries those values with it, like a small backpack.

This idea is behind many useful patterns: functions that build other functions, counters that remember their state without a class, and decorators. Closures look strange at first, but the rule is simple and you can test it with a few lines of code.

In this chapter you will learn what makes a closure, how to build function factories, how nonlocal works, how to look inside a closure, and how to avoid a famous trap with loops.

Scope refresher

Python looks for a name in this order: local scope, enclosing function scope, global scope, then built-ins. This is often called the LEGB rule. A closure uses the enclosing scope. When an inner function uses a variable from the outer function, Python keeps that variable alive for as long as the inner function exists.

Closure: an inner function together with the variables from its enclosing scope that it uses
Example 1: A simple closure
def make_greeter(greeting):
    def greet(name):
        return f"{greeting}, {name}!"
    return greet

hello = make_greeter("Hello")
hey = make_greeter("Hey")
print(hello("Asha"))
print(hey("Ravi"))
Hello, Asha! Hey, Ravi!

The function make_greeter has already finished when we call hello. Yet hello still knows its greeting. Each call to make_greeter creates a new, separate closure with its own remembered value, so hello and hey do not affect each other.

Function factories

A function that returns customised functions is called a function factory. It is a handy way to configure behaviour once and reuse it. Instead of passing the same extra argument every time, you bake it into the returned function.

Example 2: A multiplier factory
def multiplier(factor):
    def multiply(x):
        return x * factor
    return multiply

double = multiplier(2)
triple = multiplier(3)
print(double(10), triple(10))
20 30

Changing remembered values with nonlocal

An inner function can read an enclosing variable freely. But if it assigns to that name, Python thinks you are making a new local variable. To change the outer variable, declare it with nonlocal. This lets you build a counter that remembers how many times it was called, without using a class or a global variable.

Example 3: A counter with nonlocal
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())
1 2 3 1

Notice that c1 and c2 count separately. Each closure keeps its own copy of count. Without the nonlocal line, Python would raise an UnboundLocalError, because count += 1 would try to read a local variable that does not exist yet.

Looking inside a closure

Python stores the captured variables in a special attribute. A function's __closure__ is a tuple of cells, one for each captured variable, and each cell has cell_contents. The names of the captured variables are in __code__.co_freevars. A plain function that captures nothing has __closure__ equal to None.

Example 4: Inspecting captured values
def outer(a, b):
    def inner():
        return a + b
    return inner

f = outer(3, 4)
print(f.__code__.co_freevars)
print([cell.cell_contents for cell in f.__closure__])
print(outer.__closure__)
('a', 'b') [3, 4] None

The late binding trap

A closure remembers the variable itself, not the value it had at the time. If you create several functions inside a loop, they all share the same loop variable, and they see its final value when called. The usual fix is to pass the current value as a default argument, which is evaluated right away, or to use a factory function.

Example 5: Late binding and its fix
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])
[2, 2, 2] [0, 1, 2]
Closures are lighter than classes for simple state. If you need many methods or a lot of state, a class is usually clearer.

When to use a closure

Closures fit best when you need a small piece of private state or a function that is pre-configured. Because the captured variables cannot be reached from outside except through the inner function, they act like private data. This is a light way to hide details without writing a class. Think of a closure as a function with a memory of its own.

There are limits too. A closure has only one entry point, the inner function, so it is awkward when you need several operations on the same state. In that case you can return a few inner functions together, but a class usually reads better. Also be careful with large objects, because anything captured stays alive as long as the closure does.

Closures and decorators

Every decorator relies on a closure. The wrapper function remembers the original function from the decorator's scope. When you learn decorators, you are really using closures. Understanding the idea here makes that topic much easier and helps you read frameworks that return callbacks.

Python syntax

Syntax
def outer(x):
    def inner(y):
        return x + y
    return inner
Syntax
def outer():
    n = 0
    def inner():
        nonlocal n
        n += 1
        return n
    return inner

Real-world applications

  • Function factories that create configured helpers
  • Counters and accumulators without classes
  • Callbacks that remember context
  • Decorators and wrappers
  • Caching or memoising with private state

Common mistakes

Mistake: Assigning to an enclosing variable without nonlocal
Fix: Declare nonlocal name inside the inner function before changing it, or you get UnboundLocalError.
Mistake: Creating lambdas in a loop and expecting each to remember its own loop value
Fix: Bind the value with a default argument like lambda i=i: i, or build the function in a factory.
Mistake: Using global when nonlocal is needed
Fix: global refers to module-level names. For a variable in an enclosing function use nonlocal.
Mistake: Forgetting to return the inner function
Fix: Return the function without calling it, as in return inner, not return inner().

Important tips

  • Use nonlocal sparingly. Many closures only read their captured values.
  • Give factory functions clear names such as make_counter.
  • Inspect __closure__ when debugging what a function captured.
  • Prefer a class when the state and behaviour grow large.

Key points summary

  • A closure is an inner function plus the outer variables it uses.
  • Closures remember variables, not copies of values.
  • nonlocal lets an inner function change an enclosing variable.
  • Each call to the outer function creates a fresh closure.
  • Late binding in loops is fixed with default arguments.
  • __closure__ holds the captured cells.

Exam and interview points

  • Python scope order is Local, Enclosing, Global, Built-in.
  • nonlocal is required to rebind an enclosing variable.
  • Closures capture variables by reference, which causes late binding.
  • f.__closure__ is None when nothing is captured.
  • Each call of the outer function makes an independent closure.

Quick revision

  • Inner function remembers outer variables
  • Factory = function returning functions
  • nonlocal to modify enclosing variable
  • Late binding: loop lambdas share one variable
  • Fix with lambda i=i: i
  • Counters are classic closures

Frequently asked questions

What is the difference between a closure and a normal inner function?

A closure is an inner function that actually uses variables from the outer function. If the inner function uses none, nothing is captured.

What is the difference between nonlocal and global?

nonlocal works on variables in the nearest enclosing function. global works on variables at module level.

Do closures use a lot of memory?

Only the captured variables are kept alive, so the cost is small. Be careful not to capture very large objects by accident.

Why does my loop of lambdas all return the last value?

Because each lambda looks up the loop variable when called, after the loop has ended. Use a default argument to freeze the value.

Practise this chapter

18 practice questions Take the chapter quiz

Related chapters