Scope and Namespaces
Understanding Variable Scope
Variable scope defines the region of code where a variable is accessible and can be referenced. Python has four primary scopes:
graph TD
A[Python Variable Scope] --> B[Local Scope]
A --> C[Enclosing Scope]
A --> D[Global Scope]
A --> E[Built-in Scope]
Local Scope
Local scope refers to variables defined within a function:
def calculate_sum():
x = 10 ## Local variable
y = 20 ## Local variable
return x + y
result = calculate_sum()
## x and y are not accessible outside the function
Global Scope
Global variables are defined outside any function and can be accessed throughout the entire program:
total_count = 0 ## Global variable
def increment():
global total_count
total_count += 1
increment()
print(total_count) ## Outputs: 1
Namespace Hierarchy
Scope Level |
Description |
Accessibility |
Local |
Inside a function |
Limited to function |
Enclosing |
Outer function for nested functions |
Limited to outer function |
Global |
Entire module |
Entire script |
Built-in |
Python predefined names |
Entire Python environment |
Scope Resolution Rules (LEGB Rule)
Python follows the LEGB (Local, Enclosing, Global, Built-in) rule for variable lookup:
x = 10 ## Global scope
def outer_function():
x = 20 ## Enclosing scope
def inner_function():
x = 30 ## Local scope
print(x) ## Prints 30
inner_function()
print(x) ## Prints 20
outer_function()
print(x) ## Prints 10
Nonlocal and Global Keywords
def modify_variables():
x = 10 ## Local variable
def nested_function():
nonlocal x ## Allows modifying enclosing scope variable
x = 20
nested_function()
print(x) ## Prints 20
global_var = 100
def modify_global():
global global_var
global_var = 200
Practical Considerations
- Minimize global variable usage
- Use local variables when possible
- Be explicit about variable scope
- Leverage LabEx's best practices for clean code
Understanding scope and namespaces helps write more organized and predictable Python code.