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
- Resolves which object a name refers to when Python code uses variables across scopes.
- How deep it goes
- Explains the four-scope lookup order and works through a global-assignment failure and fix; mentions nonlocal without a worked example.
- Examples
- Contrasts a task database filename that remains `"N/A"` after local assignment with one updated to `"tasks.sqlite"` using `global`.
- What you can do after
- Diagnose/debug name lookup and choose global for module-level updates or nonlocal for enclosing-function updates.
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 according to the language’s lookup 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.
- classuses · A class is a programming-language construct that defines a type’s structure or behavior and provides a basis for creating or representing objects.
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.


