Sub topic 5
How Python looks up a name: the LEGB rule
This chapter assumes you can define and call functions, read a simple traceback, and that you know a name is a label attached to an object. Earlier chapters covered local and global scope separately. Here they are combined into the single lookup procedure Python runs every time your code uses a name.
The rule in one sentence
When code reads a name, Python searches four scopes in a fixed order and uses the first match:
- L, Local: names bound inside the current function.
- E, Enclosing: names bound in any function that contains the current one, searched from the innermost outward.
- G, Global: names bound at the top level of the current module (the file).
- B, Built-in: names Python provides everywhere, such as
len,print, andValueError.
If none of the four scopes has the name, Python raises NameError.
The search stops at the first match. A name found in an inner scope hides, or shadows, a name with the same spelling in an outer scope. The outer one still exists, but this lookup never reaches it.
Seeing each layer win
The following program binds x in three scopes. Each print finds the nearest one.
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x)
inner()
print(x)
outer()
print(x)
# Output:
# local
# enclosing
# globalNow remove the assignments one at a time. With no local x, inner falls through to the enclosing one.
x = "global"
def outer():
x = "enclosing"
def inner():
print(x)
inner()
outer()
# Output: enclosingWith no enclosing x either, the search reaches the module.
x = "global"
def outer():
def inner():
print(x)
inner()
outer()
# Output: globalOnly reading falls through like this. Assignment follows a different rule, covered in the next chapter.
The built-in scope
Names like len and print are not defined in your file. Python finds them in the last scope, which is the namespace of the builtins module.
import builtins
print(len is builtins.len)
print("len" in globals())
# Output:
# True
# FalseBecause the built-in scope is searched last, any name you bind earlier in the chain wins. That is how accidental shadowing of list, max, or id happens. A later chapter covers it in detail. For now, remember that built-ins are the fallback, not a special case.
When the search happens
Lookup runs when the line executes, not when the function is defined. A function body can refer to a global that does not exist yet, as long as it exists by the time the function is called.
def show():
return message
message = "hello"
print(show())
# Output: helloCalling show() before message is bound fails, because all four scopes come up empty.
def show():
return missing
try:
show()
except NameError as error:
print(error)
# Output: name 'missing' is not definedThis timing matters in practice. If you rebind a global after defining a function, the function sees the new object on its next call.
rate = 0.10
def price_with_tax(amount):
return amount * (1 + rate)
print(price_with_tax(100))
rate = 0.20
print(price_with_tax(100))
# Output:
# 110.00000000000001
# 120.0The first result shows ordinary floating-point rounding and is unrelated to scope. The function reads rate fresh on each call.
Scope is decided by where code is written
Python uses lexical scoping. Which enclosing scopes a function can see depends on where its def appears in the source, not on who calls it.
name = "global"
def get_name():
return name
def caller():
name = "caller's local"
return get_name()
print(caller())
# Output: globalget_name is written at module level, so its search goes local, then global. The local name inside caller is invisible to it, even though caller is on the call stack at that moment. Languages with dynamic scoping would print the caller's value. Python never does.
What creates a name in a scope
Lookup finds only names that something has bound. In Python, binding is wider than the = sign. These operations all bind a name in the scope where they run:
- Assignment, including augmented assignment such as
+=. forloop targets.defandclassstatements, which bind the function or class name.importstatements, which bind the module name or theasalias.with ... as nameandexcept ... as name.- Function parameters, which are bound in the function's local scope when it is called.
So a function that contains import json has a local name json. A module-level import json creates a global name that functions can read through the global step of LEGB.
Module level is a special case. At the top of a file, the local scope and the global scope are the same namespace, so the L and G steps look in the same place.
Inspecting scopes
You can look at the namespaces directly. globals() returns the module namespace as a dictionary. locals() returns the current local namespace.
city = "Oslo"
def describe(country):
capital = "Oslo"
return sorted(locals())
print(describe("Norway"))
print("city" in globals())
# Output:
# ['capital', 'country']
# TrueFor enclosing scopes, there is no dictionary to read, but the function's code object records which names it looks up how. co_freevars lists names taken from an enclosing function. co_names lists names looked up as global or built-in.
def outer():
y = 1
def inner():
return y + len([])
return inner
f = outer()
print(f.__code__.co_freevars)
print(f.__code__.co_names)
# Output:
# ('y',)
# ('len',)This works because Python classifies every name in a function when it compiles the function, before running it. That detail is the key to the next chapter.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `NameError: name 'x' is not defined` | No scope in the chain binds `x` when the line runs. Often a typo, a missing import, or a call made before the global is bound. | Check spelling and imports. Make sure the binding runs first. |
| A function returns an old or unexpected value | A nearer scope has a same-named variable that shadows the one you meant. | Rename one of them, or print `locals()` and `globals()` to see which exists. |
| A helper cannot see a caller's variable | Python scopes are lexical, so the caller's locals are not in the helper's chain. | Pass the value as an argument. |
| A method cannot see a variable defined in its class body | The class body is skipped when searching enclosing scopes. | Use `self.name` or `ClassName.name`. |
The last row is a preview. A class body creates a namespace, but functions defined inside it do not treat it as an enclosing scope. A later chapter covers this and the related rules for comprehensions.
Summary
- Python reads a name by searching Local, Enclosing, Global, then Built-in, and it uses the first match.
- A failed search raises
NameError. - Lookup happens when the line runs, so a function sees the current value of a global at call time.
- Scope follows where the code is written, not where it is called from.
- Many statements besides
=bind names, and module level is the one place where local and global scope are the same. - Python decides how to treat each name in a function when it compiles the function. This explains why assignment behaves differently from reading, which the next chapter explores.
Exercise
Predict the output of this program, and name the scope that supplies each of the three values printed. limit = 10 def outer(): scale = 2 def inner(): return len("abc") * scale + limit return inner print(outer()())
Show answer
It prints 16. The name len comes from the built-in scope, scale comes from the enclosing scope (the outer function), and limit comes from the global scope. The result is 3 * 2 + 10 = 16. Nothing is bound locally in inner, so the search for each name continues outward.
Exercise
What does this program print, and why does the local name in caller not affect getvalue? value = "module" def getvalue(): return value def caller(): value = "local to caller" return get_value() print(caller())
Show answer
It prints module. Python uses lexical scoping, so getvalue searches its own local scope and then the global scope, based on where it is defined. The value bound inside caller is local to caller and is not part of getvalue's search chain, even though caller is running when get_value is called.