Sub topic 2
How Python looks up a name: the LEGB rule
Prerequisites: defining and calling functions, basic assignment, lists, and reading a simple traceback.
How Python looks up a name: the LEGB rule
A name is a label that refers to an object. Python searches for that name in a fixed order called LEGB:
- Local: the current function.
- Enclosing: an outer function containing the current function.
- Global: the module-level namespace.
- Built-in: names such as
lenandprint.
Python stops at the first matching name.
flowchart TD
A[Name used] --> B{Local?}
B -->|yes| E[Use local object]
B -->|no| C{Enclosing?}
C -->|yes| F[Use enclosing object]
C -->|no| D{Global?}
D -->|yes| G[Use global object]
D -->|no| H{Built-in?}
H -->|yes| I[Use built-in object]
H -->|no| J[Raise NameError]Why assignment makes a name local
Python determines a function's local names when it compiles the function. If the function assigns to count anywhere, Python treats count as local throughout that function.
count = 0
def increment():
count += 1
increment()This raises UnboundLocalError. The += operation first reads the local count, but that local name has no value yet. Python does not automatically update the global name.
A function can read a global name when it does not assign to that name:
count = 0
def read_count():
return count
print(read_count()) # 0Rebinding a global with `global`
Use global when a function must rebind a module-level name.
count = 0
def increment():
global count
count += 1
increment()
increment()
print(count) # 2The statement changes which namespace receives assignments. Prefer passing values and returning results when practical, because hidden shared state makes functions harder to test.
Mutating a global object versus rebinding its name
Mutation changes an existing object. Rebinding makes a name refer to a different object.
items = []
def add_item(value):
items.append(value) # mutation; no global statement needed
def replace_items():
global items
items = [] # rebinding; global is required
add_item("a")
replace_items()
print(items) # []The method call mutates the list that items already references. Assignment to items would create a local name unless global is declared.
Exercise
Why does items.append("a") work without global, while items = [] needs it?
Show answer
The first mutates the existing list. The second rebinds the name to a new list.