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 know that assignment binds a name to an object. Here you learn the order in which Python searches for a name, and how to predict which variable a name refers to.
The four scopes
When your code uses a name such as x or len, Python searches a fixed chain of namespaces. It stops at the first one that contains the name. The initials give the rule its name, LEGB.
| Letter | Scope | Where the names live |
|---|---|---|
| L | Local | Inside the current function |
| E | Enclosing | Inside any function that wraps the current one |
| G | Global | At the top level of the current module |
| B | Built-in | Python's predefined names, such as `len` and `print` |
Seeing each level
The same name can exist in several scopes at once. The search finds the innermost one first.
level = "global"
def outer():
level = "enclosing"
def inner():
level = "local"
print(level)
inner()
print(level)
outer()
print(level)
# Output:
# local
# enclosing
# globalThere are three separate variables named level. Each print finds the nearest one. Assignments inside inner and outer created new local names. They did not change the global one.
Now remove the assignment in inner:
level = "global"
def outer():
level = "enclosing"
def inner():
print(level)
inner()
outer()
# Output: enclosinginner has no local level, so the search moves outward and finds the one in outer. If outer had no level either, Python would continue to the global one.
Built-ins and failed lookups
Names like len are not defined in your module. Python finds them in the last scope of the chain.
def size(items):
return len(items)
print(size([1, 2, 3]))
# Output: 3If the whole chain fails, Python raises NameError:
def show():
print(missing)
show()
# NameError: name 'missing' is not definedWhen the lookup happens
Python searches for a name when the line runs, not when the function is defined. The following code works because greeting exists by the time say is called:
def say():
print(greeting)
greeting = "hello"
say()
# Output: helloThe scope each name belongs to is fixed earlier, when Python compiles the function. A name that is assigned anywhere in a function body is local to that whole function. The next chapter covers that rule and the error it can cause.
Common mistakes
- Expecting an inner function to see variables of the function that called it. Enclosing scopes come from where the code is written, not from the call stack.
- Assuming that a name found in the global scope can be changed from inside a function. Reading works through LEGB, but rebinding does not.
- Reusing a built-in name like
listormaxfor your own variable. Your name is found first and hides the built-in.
Exercise
What does this code print, and which scope supplies the value of n each time?
n = 1
def f():
n = 2
def g():
return n
return g()
print(f())
print(n)
Show answer
It prints 2, then 1. Inside g, there is no local n, so the lookup finds n = 2 in the enclosing scope of f. The final print(n) runs at module level, so it finds the global n, which is still 1.
Exercise
In def show(): print(len(data)), where does Python find show, data, and len when show() runs, assuming data is defined at the top of the module?
Show answer
show is found in the global scope, because it was defined at module level. data is also found in the global scope. len is not in the local, enclosing, or global scope, so it is found in the built-in scope.