liveBook · Manning

LEGB

LEGB is Python’s name-resolution order of local, enclosing-function, global, and built-in scopes.

How 3 Manning books explain it

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.

Read how Python How-To explains LEGB →

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.

Read how Python Workout, Second Edition explains LEGB →

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

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.