Python Function Scopes
Understanding Variable Scope in Python
In Python, variable scope determines the accessibility and lifetime of variables within different parts of a program. Understanding function scopes is crucial for writing clean and efficient code.
Local Scope
Local scope refers to variables defined within a function:
def example_local_scope():
x = 10 ## Local variable
print(x) ## Accessible inside the function
example_local_scope()
## print(x) ## This would raise a NameError
Global Scope
Global variables are defined outside of any function and can be accessed throughout the entire program:
global_var = 100 ## Global variable
def demonstrate_global_scope():
print(global_var) ## Accessing global variable
demonstrate_global_scope()
Scope Hierarchy
graph TD
A[Global Scope] --> B[Enclosing Scope]
B --> C[Local Scope]
C --> D[Nested Local Scope]
LEGB Rule
Python follows the LEGB (Local, Enclosing, Global, Built-in) rule for variable resolution:
Scope Level |
Description |
Example |
Local |
Variables inside a function |
def func(): x = 10 |
Enclosing |
Variables in outer functions |
def outer(): y = 20 |
Global |
Variables defined at the module level |
global_var = 30 |
Built-in |
Python's predefined names |
len() , print() |
Modifying Global Variables
To modify a global variable inside a function, use the global
keyword:
count = 0
def increment():
global count
count += 1
increment()
print(count) ## Outputs: 1
Best Practices
- Minimize global variable usage
- Use function parameters for passing data
- Prefer local variables when possible
- Use
global
and nonlocal
keywords sparingly
By understanding function scopes, LabEx learners can write more predictable and maintainable Python code.