liveBook · Manning

Enclosing function

As explained in Python Workout: 50 ten-minute exercises

An enclosing function is a lexically surrounding function whose local bindings can be accessed by a nested function.

An enclosing function lexically surrounds a nested function and supplies bindings that the nested function can still access. This relationship creates a closure: calling the outer function produces a new inner function carrying access to the outer invocation’s variables. section 6.12

Python finds names through LEGB: local, enclosing function, global, then built-ins. A nested function searches its enclosing function’s scope after its own local scope, so separate outer invocations can preserve separate values. section 6.5 section 6.12

A closure with a private counter

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)) Each call to b updates the call_counter belonging to foo’s invocation, producing counts from 1 through 9. The nonlocal declaration allows the nested function to update that enclosing binding.

Parameterizing a returned function

def foo(x): def bar(y): return x * y return bar f = foo(10) print(f(20)) Here, bar accesses x from its enclosing invocation. The same pattern supports a password generator whose returned function remembers the allowed characters. section 6.12

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

Visualizes two password-generating functions created by separate invocations, making their retained enclosing bindings easier to compare. section 6.12

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains LEGB lookup, closure creation, separate retained bindings, and nonlocal updates through runnable examples.
Examples
Demonstrates password generators, a returned multiplier, a persistent call counter, and shadowed names.
What it assumes
Assumes familiarity with functions and variables while teaching nested-function lookup through LEGB examples.
What you can do after
Apply it via Python to build returned functions that retain configuration or mutable state across calls.
How it connects
Connects closures, nested functions, lexical scoping, LEGB, global scope, local scope, and nonlocal bindings.

Also explained in

Compare how 2 books explain enclosing function →

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.