Enclosing function
An enclosing function is a function whose body contains a nested function definition and provides a surrounding lexical scope for it.
Python Workout, Second Edition
An enclosing function is a function whose scope contains the definition or execution context of a nested function.
- How it is used
- Uses nested functions to retain invocation-specific configuration and state in returned callable objects.
- How deep it goes
- Explains nested-function creation, LEGB lookup, and nonlocal updates, stopping short of broader closure internals.
- Examples
- Demonstrates password generators, multiplication factories, call counters, shadowed built-ins, and local-versus-global names.
- What you can do after
- Build it from scratch using nested functions that retain configuration or update enclosing state with nonlocal.
Read how Python Workout, Second Edition explains enclosing function →
Python Workout: 50 ten-minute exercises
An enclosing function is a lexically surrounding function whose local bindings can be accessed by a nested function.
- How it is used
- Uses nested functions to return configurable behavior that retains values from an earlier function invocation.
- 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 you can do after
- Apply it via Python to build returned functions that retain configuration or mutable state across calls.
Read how Python Workout: 50 ten-minute exercises explains enclosing function →
Related concepts
- nonlocal statementconfigured by · A nonlocal statement makes a name assigned in a nested Python function refer to a binding in an enclosing function scope.
- inner functionhas part · An inner function is a function defined within the body or scope of another function.
- LEGBused by · LEGB is Python’s name-resolution order of local, enclosing-function, global, and built-in scopes.
- closureused by · A closure is a function or callable value together with access to bindings from the lexical environment in which it was created.
- scopepart of · Scope is the region of a program in which names are visible and can be resolved according to the language’s lookup rules.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.

