liveBook · Manning

Enclosing function

As explained in Python Workout, Second Edition

An enclosing function is a function whose scope contains the definition or execution context of a nested function.

An enclosing function is an outer function whose scope contains a nested function. The nested function can retain and use variables from the enclosing invocation after being returned. section 7.11

Use the enclosing scope to:

  • Define a new inner function each time the outer function runs. section 7.11
  • Configure returned functions with invocation-specific values, such as permitted password characters. section 7.11
  • Understand name lookup through Python’s LEGB order: local, enclosing function, global, then built-ins. section 7.5
  • Modify an enclosing variable from the nested function with the nonlocal declaration. section 7.5

A returned function retaining state

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() print(b(10)) # y = 10, call_counter = 1 print(b(20)) # y = 20, call_counter = 2 section 7.5

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

Visualize how separate invocations produce distinct password-generating functions with their own enclosing values. section 7.11

How Python Workout, Second Edition covers it

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 it assumes
Assumes familiarity with functions and calls while teaching Python’s four-level name-lookup order.
What you can do after
Build it from scratch using nested functions that retain configuration or update enclosing state with nonlocal.
How it connects
Connects closures with nested functions, variable scope, LEGB lookup, global variables, built-ins, and nonlocal variables.

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