Python Variable Scope: Local, Global, Nonlocal Rules Guide
Understanding Python variable scope local global nonlocal function nested scope rules is crucial for writing maintainable code. This comprehensive guide explains how Python resolves variable names and when to use each scope modifier.
What is Variable Scope in Python? #
Variable scope determines where variables can be accessed in your code. Python follows the LEGB Rule for scope resolution:
- Local: Inside the current function
- Enclosing: In any enclosing function
- Global: At the module level
- Built-in: In the built-in namespace
🐍 Try it yourself
Local Scope Rules #
Local variables exist only within the function where they're defined. They have the highest priority in the LEGB hierarchy.
🐍 Try it yourself
Local Variable Assignment #
When you assign to a variable inside a function, Python creates a local variable by default:
counter = 0 # Global variable
def increment():
counter = counter + 1 # This creates a local 'counter'
return counter
# This would cause UnboundLocalError
# increment()
Global Scope and the global Keyword #
Global variables are defined at the module level and can be accessed from anywhere in the module.
🐍 Try it yourself
When to Use global #
Use the global
keyword when you need to modify a global variable from within a function:
🐍 Try it yourself
Nonlocal Scope and Nested Functions #
The nonlocal
keyword allows you to modify variables in the enclosing (but not global) scope.
🐍 Try it yourself
Practical Nonlocal Example: Decorator State #
🐍 Try it yourself
Scope Resolution Examples #
Understanding how Python resolves variable names in complex scenarios:
🐍 Try it yourself
Common Scope Pitfalls #
1. Late Binding in Loops #
A common mistake when creating functions in loops:
# Problematic code
functions = []
for i in range(3):
functions.append(lambda: i) # All functions reference the same 'i'
# All functions return 2 (the final value of i)
for func in functions:
print(func()) # Prints: 2, 2, 2
Solution using default arguments:
🐍 Try it yourself
2. Modifying Global Lists vs Reassigning #
🐍 Try it yourself
Best Practices for Variable Scope #
1. Minimize Global Variable Usage #
# Instead of this:
total = 0
def add_value(value):
global total
total += value
# Prefer this:
class Calculator:
def __init__(self):
self.total = 0
def add_value(self, value):
self.total += value
2. Use Function Parameters and Return Values #
🐍 Try it yourself
3. Use Closures for State Management #
🐍 Try it yourself
Summary #
Understanding Python variable scope local global nonlocal function nested scope rules enables you to:
- Write predictable code by understanding variable resolution
- Avoid common pitfalls like unintended variable shadowing
- Use closures effectively for state management
- Choose appropriate scope modifiers (
global
,nonlocal
) when needed
Key Takeaways:
- Python follows LEGB rule for scope resolution
- Use
global
to modify module-level variables - Use
nonlocal
to modify enclosing function variables - Prefer parameter passing over global variables
- Be careful with late binding in loops and closures
Next Steps:
- Learn about Python function decorators
- Explore Python class variable scope
- Practice with variable scope code examples