liveBook · Manning

LEGB

As explained in 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.

Why does a function read a variable but fail to change it? Start by asking where Python finds the name. A scope sets a boundary for name lookup; its namespace tracks the names available there. LEGB is the order Python searches for a name’s referenced object. section 10.4.1 section 10.4

Python searches in this order and stops when it finds the name:

  • Local: the current function’s scope. section 10.4.1
  • Enclosing: an outer function’s scope, when functions are nested. section 10.4.1
  • Global: the module’s scope. section 10.4.1
  • Built-in: names such as `print` and `int`. If no scope contains the name, Python raises `NameError`. section 10.4.1

Why a database filename stays unchanged

This assignment creates a local `db_filename`; it does not update the module-level name: ```python db_filename = "N/A" def set_database(db_name): db_filename = db_name set_database("tasks.sqlite") print(db_filename) # N/A ``` To update the module-level variable, declare it `global` before assigning: ```python db_filename = "N/A" def set_database(db_name): global db_filename db_filename = db_name set_database("tasks.sqlite") print(db_filename) # tasks.sqlite ``` section 10.4 section 10.4.2

Use `global` when a function must update a module-level variable, not merely read it: an ordinary read can reach the global scope through LEGB. For a variable in an enclosing function rather than the module, the corresponding declaration is `nonlocal`. When names repeat across scopes, check which scope will supply the value—and whether the code is reading or assigning it. section 10.4.2 section 10.6 section 10.4.4

How Python How-To covers it

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 it assumes
Assumes basic Python functions and assignments while defining the lookup order and relating namespaces to scopes.
What you can do after
Diagnose/debug name lookup and choose global for module-level updates or nonlocal for enclosing-function updates.
How it connects
Connects namespaces and scopes to nested functions, global and nonlocal declarations, and NameError.

Also explained in

Compare how 3 books explain LEGB →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.