Python Variable Scope (Local, Global, Nonlocal)
1. Local Scope
def show_value():
x = 10 # Local variable
print(x)
show_value()
# print(x) # NameError: x is not definedLocal variables exist only within the function where they are declared.
2. Global Scope
x = 20 # Global variable
def display():
print(x)
display()
print(x)Global variables are accessible throughout the module.
3. Local vs Global Variable Conflict
Local variables override global variables within function scope.
4. Using the global Keyword
The global keyword allows modification of global variables inside functions.
5. Enclosing Scope (Nested Functions)
Nested functions can access variables from their enclosing scope.
6. Using the nonlocal Keyword
nonlocal allows modification of variables from the enclosing (but not global) scope.
7. LEGB Rule (Scope Resolution Order)
Python resolves variables using the LEGB rule:
Local
Enclosing
Global
Built-in
8. Built-in Scope
Built-in functions and exceptions reside in the built-in scope.
9. Scope Inside Loops
Unlike some languages, Python loop variables are not block-scoped.
10. Practical Example of Scope Management
Demonstrates coordinated use of local, enclosing, and global scopes.
78. Python Variable Scope — Local, Global, and Nonlocal (Comprehensive Guide)
1. Concept Overview
Variable scope defines where a variable is accessible and modifiable within a Python program.
Python resolves variable names using the LEGB rule:
Local – inside the current function
Enclosing – inside outer (nested) functions
Global – defined at module level
Built-in – predefined by Python
Understanding scope prevents unpredictable behavior and subtle bugs.
2. Local Scope
Variables declared inside a function are local by default.
Characteristics:
Exists only within the function
Destroyed after function execution
Safest and most predictable scope
3. Global Scope
Variables declared outside any function are global.
Characteristics:
Accessible throughout the module
Persists during program execution
Risk of unintended modification
4. Modifying Global Variables (global keyword)
global keyword)Without global, Python treats variables as local.
Use case:
Configuration management
Runtime system counters
Must be used sparingly
5. Enclosing Scope (Nested Functions)
The inner function can access variables from the enclosing function.
6. Modifying Enclosing Variables (nonlocal keyword)
nonlocal keyword)nonlocal allows nested functions to update variables from their enclosing scope.
7. LEGB Resolution Demonstration
Resolution order: Local → Enclosing → Global → Built-in
8. Shadowing Variables
Here, the local value hides the global value.
⚠️ Shadowing can cause confusion and unexpected behavior.
9. Built-in Scope
Python provides built-in identifiers:
Avoid overwriting:
This breaks core functionality.
10. Scope Behavior in Conditional Blocks
Python does not support block-level scope — variables exist at function level.
Scope Hierarchy Summary
Local
Inside function
Default
Enclosing
Nested functions
nonlocal
Global
Module-level
global
Built-in
Python engine
N/A
Variable Lifetime with Scope
Local
During function execution
Enclosing
As long as closure exists
Global
Program runtime
Built-in
Python session lifetime
Real-World Enterprise Example
Demonstrates:
Global config
Enclosing state
Closure-powered persistence
Common Mistakes
Forgetting
globalwhen updating variablesMisusing
nonlocalShadowing variables unintentionally
Overusing global data
Redefining built-in identifiers
Performance & Architectural Impact
Heavy globals
Tight coupling
Deep nesting
Reduced readability
Shadowing
Debugging complexity
Global mutation
Concurrency bugs
Best Practices
Prefer local variables
Minimize global scope usage
Use
nonlocalfor closure state onlyAvoid variable name reuse
Use function parameters instead of globals
Enterprise Importance
Mastery of variable scope ensures:
Predictable behavior
Thread-safe design
Memory efficiency
Clean modular architecture
Debug-friendly systems
Critical for:
Distributed services
AI pipelines
Concurrent systems
Financial platforms
Backend infrastructure
Comparison: Local vs Global vs Nonlocal
Accessibility
Function only
Entire module
Nested function
Modification
Direct
Requires global
Requires nonlocal
Safety
High
Low
Moderate
Architectural Value
Correct scope handling enables:
Reliable microservices
Clean dependency management
Predictable execution flow
Robust state control
Scalable codebases
Last updated