liveBook · Manning

Closure

As explained in Python Workout: 50 ten-minute exercises

A closure is a function that retains access to variables from its defining lexical environment after the enclosing function has returned.

A closure is an inner function returned by an outer function that keeps access to variables from the outer invocation. Each call to the outer function creates a separate returned function, allowing configuration to remain attached to later calls. section 6.12 section 6.5

A closure works through three connected ideas:

  • The outer function accepts configuration, such as the characters allowed in a password. section 6.12
  • The inner function uses that configuration through Python's LEGB lookup, finding variables in the enclosing function when they are not local. section 6.12 section 6.5
  • The nonlocal keyword lets the inner function update a variable stored in the enclosing function rather than create a new local variable. section 6.5

A stateful closure

def foo(): call_counter = 0 def bar(y): nonlocal call_counter call_counter += 1 return f'y = {y}, call_counter = {call_counter}' return bar b = foo() for i in range(10, 100, 10): print(b(i)) The returned function remembers call_counter between calls, producing counts from 1 through 9. section 6.5

Figure 6.3 Python Tutor’s depiction of two password-generating functions

Visualizes two separately created password-generating closures and their retained enclosing values. section 6.12

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains creation, LEGB lookup, separate instances, and nonlocal updates, without descending into runtime implementation details.
Examples
Uses configurable password generators, multiplication functions, and a call counter that preserves state across calls.
What it assumes
Assumes functions and variable scopes, while teaching enclosing-scope lookup and nonlocal assignment through examples.
What you can do after
Apply closures in Python to package configuration or preserve mutable state across function calls.
How it connects
Connects closures with nested functions, lexical scoping, LEGB lookup, and the nonlocal keyword.

Also explained in

Compare how 20 books explain closure →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.