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



















