Python Reference ยท Statements and Keywords
Scopes and the LEGB rule
How Python resolves names: Local, Enclosing, Global and Built-in scopes, assignment rules, UnboundLocalError, closures, comprehension scope and class bodies.
A scope is the region of code where a name is visible. When Python meets a name, it searches for it in a fixed order known as LEGB: the Local scope of the current function, any Enclosing function scopes, the Global (module) scope, and finally the Built-in scope. The first place where the name is found wins.
Scoping is decided by the code text, not by the call stack. Python looks at every function body when it compiles it and classifies each name: if the function assigns to a name anywhere, that name is local to the whole function.
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
How names are resolved
| Level | Where it comes from | Example |
|---|---|---|
| Local (L) | Parameters and names assigned inside the current function | total = 0 inside def |
| Enclosing (E) | Names of outer functions, for nested functions and lambdas | A counter in a closure |
| Global (G) | Names at the top level of the module (the file) | Constants, functions, classes |
| Built-in (B) | The builtins module |
len, print, ValueError |
Reading a name uses the search above. Assigning, augmenting, del and import create or rebind a name in the current scope unless a global or nonlocal statement says otherwise.
Usage notes
- Only these construct new scopes: functions (including lambdas), classes, comprehensions and generator expressions, and modules.
if,for,while,withandtrydo not. - Class bodies have their own namespace, but methods do not see it as an enclosing scope. Inside a method, use
self.nameorClassName.name. UnboundLocalError(a subclass ofNameError) means the name is local to this function but has not been assigned yet. Addglobalornonlocal, or use a different local name.- Mutation needs no declaration.
items.append(1)works on a global list, because no name is rebound. - Shadowing built-ins such as
list,sum,idortypeis legal and a frequent source of confusing errors. Rename the variable. - Closures are late binding. They look up the variable when called, not when defined. Bind with a default argument (
lambda k=k: k) to capture the current value. - Inspect namespaces with
globals(),locals()anddir(). - Python 3.12 (PEP 709) inlined comprehensions for speed, but their loop variables remain private to them.