Variable Scope and the LEGB Rule
Master variable visibility in Python using the LEGB rule (Local, Enclosing, Global, Built-in), understanding namespaces, global, and nonlocal keywords.
Imagine you are working in an office building:
- A sticky note stuck on your private desk has the word
phone = "555-0199"written on it. Only you can see it and use it. - A whiteboard in your departmentโs hallway has
deadline = "Friday"written on it. You and your immediate teammates can see it. - A bulletin board in the buildingโs lobby displays
company_name = "TechCorp". Everyone in the entire company can see it. - Finally, national laws and emergency exit signs apply to every building in the country.
If your teammate also has a sticky note on their desk with phone = "555-0144", your notes do not collide or overwrite each other. Each note lives in its own private space.
In programming, this boundary of variable visibility is called Scope.
1. The LEGB Lookup Hierarchy
Whenever Python encounters a variable name in your code, it searches for that name across four distinct namespaces in a strict, fixed order known as the LEGB Rule:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 1. [L] Local Scope (Inside current function) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ 2. [E] Enclosing Scope (Any outer parent function) โ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ โ 3. [G] Global Scope (Top-level of module file)โ
โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ โ โ 4. [B] Built-in (print, len, range, int) โ
โโโโโโดโโโโโดโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
- L - Local: Variables defined inside the currently running function or lambda.
- E - Enclosing: Variables defined in an outer function that wraps the current nested function.
- G - Global: Variables defined at the top level of the current
.pyscript or module. - B - Built-in: Reserved names pre-loaded by Python itself (
print(),len(),range(),int(), etc.).
If Python checks all four levels and still cannot find the variable, it raises a NameError: name 'x' is not defined.
2. Local Scope: Privacy by Default
Any variable created inside a function is local to that function. It is born when the function executes and destroyed as soon as the function finishes:
def calculate_tax(income):
tax_rate = 0.20 # Local variable!
return income * tax_rate
total_tax = calculate_tax(50000)
print("Tax calculated:", total_tax)
# DANGER: tax_rate does not exist outside the function!
# print(tax_rate) # NameError: name 'tax_rate' is not defined
Local scope protects you. You can use common variable names like x, i, count, or temp inside ten different functions without worrying about them interfering with one another.
3. Global Scope and the Reading vs Writing Trap
A variable defined at the top level of your script (outside any function) is global. Any function in the file can read it:
app_title = "RoadmapPro Engine" # Global variable
def show_header():
# Reading global variable works effortlessly
print(f"=== {app_title} ===")
show_header()
The UnboundLocalError Trap: Attempting to Modify a Global
Look at what happens when you try to change a global variable inside a function:
visit_count = 0
def record_visit():
# Attempting to increment global variable:
visit_count += 1
# record_visit()
# UnboundLocalError: cannot access local variable 'visit_count' where it is not associated with a value!
Why did this crash?
When Python parses the function, it sees the assignment operator (visit_count += 1 is shorthand for visit_count = visit_count + 1). Because an assignment exists, Python immediately decides that visit_count must be a local variable.
Then, when it tries to evaluate visit_count + 1, the local variable has not been given a value yet!
4. The global Keyword
To tell Python that you explicitly intend to modify the module-level global variable rather than creating a new local variable, declare it with the global keyword:
visit_count = 0
def record_visit():
global visit_count # Explicitly bind to the global variable
visit_count += 1
record_visit()
record_visit()
record_visit()
print("Total visits recorded:", visit_count) # 3
[!WARNING] While
globalworks, professional engineers avoid it whenever possible. Modifying global variables creates โspooky action at a distanceโ: any function can change state behind the scenes, making bugs notoriously difficult to track.Best Practice: Pass inputs as function arguments and return updated values:
def increment(count): return count + 1 visit_count = increment(visit_count)
5. Enclosing Scope & The nonlocal Keyword
When you place a function inside another function (a nested function or closure), the outer functionโs variables form the Enclosing scope:
def make_counter():
count = 0 # Enclosing scope for inner()
def inner():
nonlocal count # Binds to the enclosing 'count' variable
count += 1
return count
return inner
# Create independent counter instances
counter_a = make_counter()
print(counter_a()) # 1
print(counter_a()) # 2
counter_b = make_counter()
print(counter_b()) # 1 (separate enclosing closure!)
Without nonlocal count, Python would treat count = count + 1 inside inner() as an assignment to an uninitialized local variable, raising UnboundLocalError.
6. Shadowing Built-Ins: The Name Collision Bug
Because Built-in is the last step in the LEGB hierarchy, defining a local or global variable with the same name as a Python built-in will shadow (mask) it:
# DANGEROUS MISTAKE: Never name a variable after a built-in!
list = [10, 20, 30]
# Later in your code:
# names = list("ABC")
# TypeError: 'list' object is not callable!
Because Python found list in the Global scope, it stopped looking and never reached the Built-in list() constructor!
Common built-in names to avoid using as variables:
id,type,list,dict,set,str,int,len,max,min,sum,input.
Summary & Practice
| Scope | Where it lives | Lifetime | Keyword to modify |
|---|---|---|---|
| Local (L) | Inside a function | While function executes | Default for assignments |
| Enclosing (E) | Outer enclosing function | Persists inside closures | nonlocal |
| Global (G) | Module file top-level | Entire script execution | global |
| Built-in (B) | Python language core | Always present | Do not overwrite! |
Now that you understand variable visibility and function lifecycles, letโs learn how to write functions that accept an arbitrary, unlimited number of arguments in args-kwargs.