π§ 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
global
andnonlocal
π 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
nonlocal
only when necessary for closures - β
Avoid using
global
unless 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.
- β
global
lets you write to global variables inside functions. - β
nonlocal
allows 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 :