liveBook · Manning

Closure

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

A closure is a function together with references to variables from its enclosing lexical scope.

A closure is a function that references a variable from its enclosing lexical scope. Defining a function inside another function limits its visibility to the enclosing function while allowing it to use captured values. section 8.3.2 section 8.6

Replacing vowels with a captured value

def main(): vowel = 'o' def new_char(c): return vowel if c in 'aeiou' else vowel.upper() if c in 'AEIOU' else c text = 'Apples and Bananas!' print(''.join(new_char(c) for c in text)) main() # Opplos ond Bononos! new_char() uses vowel without receiving it as an argument, so it closes around vowel. Code outside main() cannot call new_char(). section 8.3.2

Closures become useful when a small function needs local configuration:

  • Capture command-line values such as a replacement vowel instead of passing them through every call. section 8.3.2
  • Define a predicate inside main() that remembers minimum and maximum word lengths while filter() processes words. section 20.1.4
  • Compare closures with explicit parameters: the latter can be easier to understand and unit-test in some cases. section 8.3.2
Figure 8.6 The new_char() function can only be seen within the main() function. It creates a closure because it references the vowel variable. Code outside of main() cannot see or call new_char().

Use the visibility example to see that new_char() exists only within main() and captures vowel from that scope. section 8.3.2

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains nested scope, visibility, and captured variables through runnable examples, but does not descend into runtime implementation.
Examples
Demonstrates vowel replacement with new_char() and word-length filtering with word_len().
What it assumes
Assumes basic functions and variables while teaching nested-function visibility and references to enclosing-scope variables.
What you can do after
Apply it via Python nested functions to retain local values inside transformation and filtering callbacks.
How it connects
Connects closures with lexical scope, nested functions, lambda expressions, map(), and filter().

Also explained in

Compare how 20 books explain closure →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.