liveBook · Manning

Closure

As explained in Python Workout, Second Edition

A closure is a function that retains access to variables from an enclosing function scope after that enclosing function has returned.

A closure is an inner function returned by an outer function that retains access to variables in the enclosing scope after the outer call ends. Each invocation of the outer function creates a new inner function and its captured values. section 7.11 section 7.5

A multiplier closure

def foo(x): def bar(y): return x * y return bar f = foo(10) print(f(20)) # 200 The returned function keeps access to x, even though foo has returned. Calling foo again creates another closure with its own enclosing value. section 7.5

Use closures when a returned function needs private configuration or persistent state:

  • Capture configuration, such as allowed password characters, while exposing only the returned generator function. section 7.11
  • Maintain state with nonlocal: assign to the enclosing variable instead of creating a new local variable. section 7.5
  • Apply LEGB when diagnosing name resolution: Python checks the local, enclosing, global, and built-in namespaces in order. section 7.5
Figure 7.2 Python Tutor’s depiction of two password-generating functions
figure

Visualize two password-generating closures and compare the separate functions created by separate outer invocations. section 7.11

How Python Workout, Second Edition covers it

How deep it goes
Explains nested-function creation, LEGB lookup, separate invocations, and nonlocal assignment, stopping short of deeper runtime internals.
Examples
Demonstrates multiplier functions, password generators, and a call-counting closure.
What it assumes
Assumes familiarity with Python functions and teaches nested scopes through LEGB before applying nonlocal.
What you can do after
Build closures that capture arguments, generate configured functions, or update enclosing state with nonlocal.
How it connects
Connects closures with inner functions, lexical scoping, LEGB, nonlocal variables, and Python decorators.

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, Second Edition. The section links point to the parts of the book it draws on.