LEGB
LEGB is Python’s name-resolution order of local, enclosing-function, global, and built-in scopes.
Python How-To
The LEGB rule is Python's name-resolution rule that searches local, enclosing-function, global, and built-in scopes in that order.
- How it is used
- Explains how Python resolves names and helps diagnose attempts to change variables across scopes.
- How deep it goes
- Defines the lookup sequence and works through local versus global assignment, including the global declaration.
- Examples
- Uses a database filename setter that first leaves a global unchanged, then updates it with a global declaration.
- What you can do after
- Diagnose/debug cross-scope name resolution and identify when global or nonlocal is needed for an assignment.
Python Workout, Second Edition
The LEGB rule is Python's variable-lookup order of local, enclosing, global, and built-in scopes.
- How it is used
- Explains how Python resolves names inside and outside functions.
- How deep it goes
- Defines four lookup levels and works through shadowing, global rebinding, closures, and nonlocal state.
- Examples
- Uses nested functions, password generators, inner and outer x values, sum shadowing, and a nonlocal call counter.
- What you can do after
- Diagnose name-resolution surprises and choose local, global, or nonlocal bindings deliberately.
Python Workout: 50 ten-minute exercises
LEGB is Python's name-resolution order of local, enclosing-function, global, and built-in scopes.
- How it is used
- Explains Python name visibility, shadowing, nested-function behavior, and closure state.
- How deep it goes
- Defines lookup order and demonstrates closures and shadowing, while stopping short of a broader namespace implementation treatment.
- Examples
- Uses shadowed sum, inner-versus-outer variables, password generators, and functions retaining enclosing values.
- What you can do after
- Diagnose name-resolution errors, predict variable visibility, and design functions that retain enclosing state.
Read how Python Workout: 50 ten-minute exercises explains LEGB →
Related concepts
- scopeconfigures · Scope is the region of a program in which names are visible and can be resolved to their bindings according to the language’s rules.
- ICPOcontrasts with · ICPO is a mnemonic for Python attribute lookup order across an instance, its class, parent classes, and the object hierarchy.
- bindinguses · Name binding is the association of an identifier with the program entity or value it denotes.
- enclosing functionuses · An enclosing function is a function whose body contains a nested function definition and provides a surrounding lexical scope for it.
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.


