The LEGB rule describes the order in which Python searches for a name when you reference a variable. The four scopes are checked in sequence: Local (the innermost function body), Enclosing (the bodies of any enclosing functions, from inner to outer), Global (the module-level namespace), and Built-in (the builtins module containing names like print, len, and True).
When Python encounters a name, it starts at the Local scope. If the name is not found there, it moves to the Enclosing scope (relevant only for nested functions), then to the Global scope, and finally to the Built-in scope. If the name is not found in any scope, Python raises a NameError. This lookup happens at runtime, not at compile time — though the compiler does determine which scope a name belongs to based on whether it is assigned within the function.
The LEGB rule interacts with the global and nonlocal keywords. global x tells Python to treat x as a global variable within the function, bypassing Local and Enclosing. nonlocal x tells Python to find x in the nearest Enclosing scope. These keywords are only needed for assignment; reading from an outer scope works automatically via LEGB lookup. Closures rely on Enclosing scope capture, making LEGB the foundation of Python's scoping model.
Discussed in:
- Chapter 5: Functions — Scope and the LEGB Rule