🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Python Closures: nonlocal, Cells, and Factory Functions

Python FunctionsđŸŸĸ Free Lesson

Prerequisites

  • !Nested functions, LEGB scoping, and free variables
  • !Functions as first-class objects in Python

What You'll Learn

  • 1Explain what a closure captures and where the captured state lives
  • 2Tell mutation of a shared object apart from rebinding a name
  • 3Build factory functions for counters, validators, and memoizers
  • 4Inspect a live closure with __closure__ and co_freevars
  • 5Choose between a closure and a small class with confidence

A function in Python remembers the scope it was created in, not the scope it is called from. That single rule explains a family of patterns you have probably written without naming them: decorators that carry configuration, handlers that capture one row of data, counters that survive across calls. Before reaching for a class every time state and behaviour need to travel together, it pays to understand what the interpreter actually stores, why rebinding behaves differently from mutation, and where a closure is genuinely the cleaner design.

What the inner function keeps alive

Python resolves names through the LEGB chain: local, enclosing, global, built-in. When the compiler sees a name inside a nested function that is never assigned locally and does not exist at module level, it flags that name as a free variable and records that it must be looked up in an enclosing function's frame. The inner function does not copy anything at definition time. It holds a reference into the outer frame, and that reference is what keeps the frame alive after the outer function returns.

Two consequences follow. First, mutation is shared and rebinding is local, which is the source of most closure bugs. Second, memory is held for as long as the closure itself lives. A returned function that casually closes over a database connection, a compiled regex corpus, or a fifty-megabyte dataframe keeps that object reachable even when your application logic no longer needs it. When you build long-lived handlers, prefer capturing a small key or identifier and look the heavy object up when the handler runs.

Because every call of the outer function creates a fresh frame, each closure returned by the same factory owns its own private state. Two counters built from one factory never interfere, which is precisely the behaviour you want for rate limiters, per-request context, and per-user caches. Shared state only appears when several closures are created inside the same outer call, and in that case they deliberately point at the same cell.

Reading the cells a closure stores

You do not need a debugger to see what a closure captured. Every function object exposes its cells through the __closure__ tuple and the names of those free variables through __code__.co_freevars. The two lists are positionally aligned, so the first name belongs to the first cell. Reading cell_contents is one of the clearest ways to answer a bug report that says "this function remembers the wrong value".

python
def make_counter(start=0):
    count = start

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

    return counter


counter = make_counter(10)
print(counter(), counter(), counter())   # 11 12 13

print(counter.__code__.co_freevars)      # ('count',)
print(counter.__closure__[0].cell_contents)  # 13

other = make_counter(100)
print(other(), counter())                # 101 14

Notice that other and counter share no cells: they were produced by separate calls, so each one owns a distinct count. If you later wrap counter inside a decorator, the wrapper usually preserves __wrapped__ and often forwards __closure__, but hand-written wrappers frequently drop it. When a decorated function suddenly loses its memory, check the closure chain first.

Mutation needs no keyword, rebinding does

This is the distinction that trips up almost everyone. If the inner function only reads a free variable, or only calls methods on the object it refers to, Python needs no permission. If it assigns to the name itself, the compiler would treat that assignment as a local variable, and reading before that assignment raises an error. The nonlocal declaration tells the compiler to write to the existing enclosing binding instead of creating a new local one.

Inner function actionExampleName read first?Needs nonlocal
Read a free variablereturn countYesNo
Mutate the referenced objectseen.append(item)YesNo
Assign into a containertable[key] = valueNo (subscript)No
Rebind the free variablecount = count + 1YesYes
Rebind inside a nested helpercount += 1 in a child functionYesYes, in that child
python
def broken_averager(values):
    total = 0

    def add(value):
        total = total + value      # UnboundLocalError at first call
        values.append(value)
        return total / len(values)

    return add


def working_averager(values):
    total = 0

    def add(value):
        nonlocal total
        total += value
        values.append(value)
        return total / len(values)

    return add

The first version fails because the assignment makes total local to add, so the right-hand side reads a name that does not exist yet. The second version is the correct pattern, but note that it still needs values to be an object it can mutate. If you want both pieces of state to be rebound, you need nonlocal for each of them, one declaration per name.

Factories: one template, many configured behaviours

The most productive use of closures is the factory: a function that takes configuration and returns a purpose-built callable. Factories are ideal when the configuration is fixed at creation time and the returned object is small, so a class would only add ceremony.

python
def make_clamp(low, high):
    def clamp(value):
        if value < low:
            return low
        if value > high:
            return high
        return value

    clamp.__doc__ = f"Clamp a value to the range {low}..{high}"
    return clamp


def make_validator(**checks):
    def validate(record):
        problems = []
        for name, rule in checks.items():
            if name in record and not rule(record[name]):
                problems.append(name)
        return problems

    return validate


clamp01 = make_clamp(0, 1)
score = make_validator(age=lambda v: v >= 0, email=lambda v: "@" in v)

print(clamp01(-5), clamp01(3), clamp01(0.5))   # 0 1 0.5
print(score({"age": -1, "email": "[email protected]"}))    # ['age']

Each factory call produces an independent function object with its own captured variables, so you can ship clamp01 and a clamp80 to different parts of a program without any shared mutable configuration. This is also the shape behind functools.partial, functools.lru_cache wrappers, and the classic decorator-with-arguments idiom: an outer function that receives the arguments and an inner function that receives the call.

Closures or a small class: deciding honestly

Both designs work. The right question is which one communicates your intent with less machinery.

ConcernClosureSmall class
Amount of stateOne or two captured valuesSeveral related fields
Methods per state setOne callableMany methods
IntrospectionNames hidden in cellsAttributes visible on the instance
Identity and equalityFunction identityYou define __eq__
Pickling and copyingFunctions pickle poorlyUsually straightforward
Readability for newcomersFamiliar in callbacksFamiliar in domain models

Reach for a closure when you are producing a single configured behaviour: a key function for sorted, a one-shot callback, a policy passed to a worker. Reach for a class when the same state supports several operations, when you need to expose attributes for logging or serialization, or when other developers must discover the state by reading the code. A class with three methods and no inheritance is clearer than a closure that attaches attributes to a function object with assignments like counter.reset = ..., a trick that works but hides the interface from every tool that inspects classes.

Where closures show up in real code

Once you can name the mechanism, you start spotting it everywhere. A decorator that takes options and returns a wrapper is a factory whose captured state is the option set. A callback registered with button.on_click(handler) usually closes over the record that handler must edit. A thread worker created in a loop captures the loop variable only if you rebind it first, which is why the classic advice is to pass the value as a default argument. Closures are also the backbone of memoization: the cache lives in the enclosing function, and the wrapper reads it on every call.

The practical skill is reading someone else's closure and deciding what it holds. Start with co_freevars to list the names, then read each cell. If the list looks longer than the job requires, the closure is probably dragging objects along with it.

Common Mistakes

Assuming the closure captured a snapshot of a variable's value

Fix: Remember that the cell holds a reference; copy explicitly with list() or dict() if you need an independent snapshot at creation time.

Rebinding a free variable without declaring nonlocal, then chasing UnboundLocalError

Fix: Add nonlocal for every name the inner function assigns, or move the state into a small mutable container such as a one-element list.

Returning a closure that keeps a huge object alive for the whole process lifetime

Fix: Capture a small key instead and look the heavy resource up inside the function, or break the reference when the work is done.

Attaching methods to a function object to avoid writing a class

Fix: If the interface grows past one behaviour, promote it to a class so that tools, type checkers, and readers can see the API.

Best Practices

  • Name the inner function so tracebacks and profiler output stay readable
  • Prefer nonlocal over the one-element list trick because it keeps the value's real type
  • Expose captured state through a debug helper that prints co_freevars and cell contents
  • Keep factories shallow: configuration in, one behaviour out
  • Write a test that creates two closures and proves they do not share state

Key Takeaways

  • A closure stores references into the enclosing frame, which is why mutations are visible and frames stay alive
  • cell objects hold free variables and can be read through __closure__ and co_freevars
  • Mutation of a captured object needs no keyword; rebinding the name requires nonlocal
  • Factories turn configuration into a purpose-built callable with independent state per call
  • Choose a class once the same state must support several methods or be inspected and serialized
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement