Understanding Python’s Scope and the LEGB Rule
When writing Python code, understanding how and where variables are resolved is crucial. Python uses a well-defined rule called LEGB to determine the scope of a variable.
📘 What is Scope in Python?
Scope refers to the area of your program where a variable is recognized. Depending on where you declare a variable, it may or may not be accessible from other parts of your code.
🧭 The LEGB Rule: Python’s Name Resolution Order
When you reference a variable in Python, the interpreter looks for it in the following order:
| Level | Description |
|---|---|
| L – Local | Inside the current function |
| E – Enclosing | Inside enclosing (outer) functions |
| G – Global | At the top level of the current script/module |
| B – Built-in | Python’s built-in names (e.g., print, len) |
🧪 Let’s Explore Each Scope with Examples
🔹 1. Local Scope
Variables defined inside a function are in the local scope.
def greet():
name = "Alice" # Local
print(name)
greet() # Output: Alice🔹 2. Enclosing Scope
A function inside another function can access variables from its enclosing (outer) function.
def outer():
msg = "Hello from outer"
def inner():
print(msg) # Enclosing
inner()
outer() # Output: Hello from outer🔹 3. Global Scope
Variables defined outside any function are in the global scope.
name = "Global Name"
def show_name():
print(name) # Global
show_name() # Output: Global Name🔹 4. Built-in Scope
Python comes with built-in functions and constants like len(), max(), and print().
print(len("Hello")) # Output: 5💡 Example Using All Four Scopes
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x) # Will print "local"
inner()
outer()If you remove the line x = "local", then inner() will print "enclosing". If that’s removed too, it prints "global".
❗️What Happens If a Variable is Not Found?
Python checks L → E → G → B. If the variable is not found in any of these scopes, it raises a NameError.
def test():
print(y) # Not defined
test() # NameError: name 'y' is not defined🛠 Bonus: Changing Variables in Global and Enclosing Scope
Use global or nonlocal if you need to modify variables from other scopes.
✅ Using global
x = 5
def modify():
global x
x = 10
modify()
print(x) # Output: 10✅ Using nonlocal
def outer():
count = 0
def inner():
nonlocal count
count += 1
print(count)
inner()
outer() # Output: 1🧠 Summary Table
| Scope | Keyword | Example Context |
|---|---|---|
| Local | — | Variable inside function |
| Enclosing | nonlocal | Variable in outer function |
| Global | global | Variable at module level |
| Built-in | — | Built-in names like len() |
📝 Final Thoughts
Mastering Python’s LEGB rule helps you write bug-free, predictable, and clean code—especially when dealing with nested functions, global variables, or closures.

Comments are closed.