Python Scope Explained – LEGB Rule, Global, Nonlocal, Best Practices
Introduction – Why Variable Scope Matters
In Python, scope refers to the area of a program where a variable is recognized and accessible. When your code contains nested functions, global declarations, or built-in names, understanding which variable Python is referring to is crucial.
Python follows a specific LEGB rule to resolve variable names:
- L – Local
- E – Enclosing
- G – Global
- B – Built-in
Misunderstanding scope often leads to hard-to-find bugs or UnboundLocalError. This guide will help you master scope and avoid such pitfalls.
In this guide, you’ll learn:
- The 4 scopes in Python defined by the LEGB rule
- How Python looks up variables
- Real-world examples of scope in nested functions
- When and how to use
globalandnonlocal
The LEGB Rule Explained
L – Local Scope
Defined inside a function and accessible only within that function.
def func():
x = 10 # local scope
print(x)
E – Enclosing Scope
Variables from outer functions in nested functions.
def outer():
y = "enclosing"
def inner():
print(y) # enclosing scope
inner()
G – Global Scope
Defined at the top level of a script or module.
x = "global"
def func():
print(x) # global variable
B – Built-in Scope
Names preassigned in Python—like len, sum, print, etc.
print(len("Python")) # Built-in function
Scope Lookup Order
When you access a variable, Python searches in this order:
- Local (inside current function)
- Enclosing (in outer functions)
- Global (at module level)
- Built-in (Python reserved names)
As soon as Python finds a match, it stops searching.
Example: LEGB in Action
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x)
inner()
outer() # Output: local
Explanation: The innermost assignment wins due to the LEGB search hierarchy.
Using global Keyword
Modifies global variables inside functions.
count = 0
def increment():
global count
count += 1
Use global sparingly—it makes code harder to debug and test.
Using nonlocal Keyword
Modifies variables in enclosing (non-global) scope.
def outer():
x = 10
def inner():
nonlocal x
x += 1
print(x)
inner()
outer() # Output: 11
Useful for closures and decorators where the inner function needs to update outer variables.
Common Pitfalls
| Issue | Example | Fix |
|---|---|---|
UnboundLocalError | Using a variable before assigning | Declare variable before use |
Overusing global | Frequent global mutations | Return values instead |
| Shadowing built-ins | Using sum = 10 | Avoid overwriting built-ins |
Best Practices
- Keep variables local whenever possible
- Use
nonlocalonly when necessary for closures - Avoid using
globalunless absolutely required - Never shadow built-in names like
list,str,sum
Summary – Recap & Next Steps
Python uses the LEGB rule (Local, Enclosing, Global, Built-in) to determine variable scope and resolve names during execution. Understanding how this rule works ensures you write clean, predictable, and bug-free code.
Key Takeaways:
- Variables are resolved in the order: Local → Enclosing → Global → Built-in.
-
globallets you write to global variables inside functions. -
nonlocalallows writing to variables in enclosing (outer) functions. - Scope clarity is essential for nested functions and closures.
Real-World Relevance:
Scope handling is critical in functional programming, decorators, closures, and frameworks like Flask/Django, where multiple nested functions share context.
FAQ Section – Python Scope (LEGB)
What is scope in Python?
Scope determines where a variable can be accessed. Python uses LEGB—Local, Enclosing, Global, and Built-in—to resolve variable names.
What does LEGB stand for?
LEGB refers to the order Python searches for variable names:
Local → Enclosing → Global → Built-in.
What is a global variable?
A global variable is defined at the top level of a Python script and is accessible from any function (unless shadowed).
How do I modify a global variable inside a function?
Use the global keyword:
global x What is nonlocal used for?
The nonlocal keyword allows modification of variables from an enclosing (non-global) scope, typically used in nested functions.
Share Now :
