Basics of Variable Scope
Understanding Variable Scope in Python
In Python, variable scope determines the accessibility and lifetime of a variable within different parts of a program. Understanding variable scope is crucial for preventing undefined variable errors and writing clean, efficient code.
Types of Variable Scope
Python primarily has three types of variable scopes:
1. Local Scope
Variables defined inside a function have local scope and are only accessible within that function.
def example_function():
local_var = 10 ## Local variable
print(local_var) ## Accessible here
example_function()
## print(local_var) ## This would raise an NameError
2. Global Scope
Variables defined outside of any function have global scope and can be accessed throughout the entire script.
global_var = 20 ## Global variable
def access_global():
print(global_var) ## Accessible inside the function
access_global()
print(global_var) ## Accessible outside the function
3. Nonlocal Scope
Used in nested functions to refer to variables in the outer (enclosing) function's scope.
def outer_function():
x = 10
def inner_function():
nonlocal x
x = 20 ## Modifies the outer function's x
inner_function()
print(x) ## Prints 20
outer_function()
Scope Resolution Order (LEGB Rule)
Python follows the LEGB rule for variable lookup:
graph TD
A[Local Scope] --> B[Enclosing Scope]
B --> C[Global Scope]
C --> D[Built-in Scope]
Scope Level |
Description |
Local (L) |
Inside the current function |
Enclosing (E) |
Inside enclosing functions |
Global (G) |
At the top level of the module |
Built-in (B) |
Python's built-in namespace |
Best Practices
- Use local variables when possible
- Minimize global variable usage
- Use
global
and nonlocal
keywords carefully
- Be explicit about variable scope
Common Pitfalls
x = 10 ## Global variable
def modify_x():
x += 1 ## This will raise an UnboundLocalError
## Python treats x as a local variable due to assignment
def correct_modify_x():
global x
x += 1 ## Now this works correctly
At LabEx, we recommend understanding these scope principles to write more robust and predictable Python code.