What is the LEGB Rule (Scope) in Python?
Understand Python's LEGB rule for scope: how Local, Enclosing, Global and Built-in namespaces resolve names, plus global vs nonlocal with clear examples.
Expected Interview Answer
The LEGB rule describes the order Python searches namespaces to resolve a name: Local, then Enclosing, then Global, then Built-in. The first scope where the name is found wins.
When you reference a variable, Python looks first in the current function's Local scope, then in any Enclosing function scopes, then the module-level Global scope, and finally the Built-in namespace. Assignment inside a function creates a Local name by default, which is why you need the global or nonlocal keyword to rebind names in outer scopes. This lookup chain determines which value a name maps to at runtime.
- Explains predictable name resolution
- Prevents accidental variable shadowing bugs
- Clarifies when to use global and nonlocal
- Underpins how closures capture variables
- Makes debugging NameError and UnboundLocalError easier
AI Mentor Explanation
Finding who takes the next catch follows a chain of authority: first the fielder right there (Local), then the on-field captain (Enclosing), then the team's head coach (Global), and finally the ICC rulebook (Built-in). Python resolves a name the same way, stopping at the first level that answers.
Step-by-Step Explanation
Step 1
Check Local
Python first looks for the name in the current function or comprehension's own namespace.
Step 2
Check Enclosing
If not found locally, it searches any enclosing function scopes from innermost outward (relevant to closures).
Step 3
Check Global
Next it looks at the module-level namespace where top-level names and imports live.
Step 4
Check Built-in
Finally it searches the built-in namespace containing names like len, print, and range.
Step 5
Rebind with keywords
Use global to assign to a module-level name or nonlocal to assign to an enclosing scope name from inside a function.
What Interviewer Expects
- Correct expansion of L, E, G, B in order
- Understanding that assignment defaults to Local scope
- Knowing when global vs nonlocal is needed
- Connecting enclosing scope to closures
- Explaining UnboundLocalError with an example
Common Mistakes
- Reversing the order (searching Global before Local)
- Thinking a bare assignment updates a global variable
- Confusing nonlocal with global
- Believing loops or if-blocks create new scopes
- Forgetting that comprehensions have their own local scope in Python 3
Best Answer (HR Friendly)
“LEGB is just the order Python uses to figure out what a variable name refers to: it checks the local function first, then any function around it, then the whole file, and finally Python's built-in names. It uses the first match it finds.”
Code Example
x = "global" # Global
def outer():
x = "enclosing" # Enclosing
def inner():
x = "local" # Local
print(x) # -> local
inner()
print(x) # -> enclosing
outer()
print(x) # -> global
print(len) # -> Built-in name still visible
def counter():
count = 0
def bump():
nonlocal count # rebind the enclosing 'count'
count += 1
return count
return bump
c = counter()
print(c(), c()) # -> 1 2Follow-up Questions
- What is the difference between global and nonlocal?
- Why does assigning to a variable inside a function cause UnboundLocalError?
- How does the LEGB rule relate to closures?
- Do list comprehensions create their own scope in Python 3?
- What names live in the built-in namespace and how can you inspect them?
MCQ Practice
1. What does LEGB stand for in the correct search order?
Python searches Local first, then Enclosing, then Global, then Built-in, stopping at the first match.
2. Which keyword lets an inner function rebind a variable defined in an enclosing (but not global) function?
nonlocal binds to the nearest enclosing function scope; global binds to the module-level namespace.
3. By default, assigning to a name inside a function creates a name in which scope?
Assignment inside a function creates a local name unless global or nonlocal is declared.
Flash Cards
What does LEGB stand for? — Local, Enclosing, Global, Built-in — the order Python searches namespaces for a name.
What scope does a bare assignment in a function use? — Local — unless you declare the name global or nonlocal.
global vs nonlocal? — global rebinds a module-level name; nonlocal rebinds the nearest enclosing function's name.
Which scope holds len and print? — The Built-in namespace, searched last in the LEGB chain.