In Python, variables can have different scopes, which determine where in the code they can be accessed. The primary scopes are global scope, local scope, and enclosing scope. Understanding these scopes is essential to managing variables effectively and avoiding bugs due to unintended changes.
Global scope
A variable has a global scope if it is defined outside of any function or block. These variables are accessible from anywhere in the code, including inside functions, unless a variable with the same name is redefined locally.
Example:
# Global variable
message = "Hello, World!"
def greet():
print(message) # Accessing the global variable
greet() # Output: Hello, World!
print(message) # Output: Hello, World!
Here, message
greet()
Modifying global variables
To modify a global variable inside a function, you need to declare it as global
count = 10 # Global variable
def increment_count():
global count
count += 1
increment_count()
print(count) # Output: 11
Using the global
increment_count()
count
.
Local scope
A local scope refers to variables defined within a function. These variables can only be accessed within the function they are defined in and are not visible outside.
Example:
def greet():
message = "Hello from the function!" # Local variable
print(message)
greet() # Output: Hello from the function!
# Trying to access message outside the function raises an error
print(message) # Error: NameError: name 'message' is not defined
In this case, message
is local to the greet()
Enclosing scope (nested functions)
When functions are nested inside other functions, the outer function's variables are in an enclosing scope. An inner function can access these variables but cannot modify them unless the nonlocal
Example:
def outer_function():
outer_message = "Hello from the outer function!"
def inner_function():
print(outer_message) # Accessing variable from the enclosing scope
inner_function()
outer_function()
# Output: Hello from the outer function!
Here, outer_message
outer_function()
inner_function()
Modifying enclosing scope variables with nonlocal
To modify a variable from an enclosing function inside an inner function, use the nonlocal
def outer_function():
counter = 0
def inner_function():
nonlocal counter # Modify the enclosing variable
counter += 1
print(counter)
inner_function() # Output: 1
inner_function() # Output: 2
outer_function()
Here, nonlocal
inner_function()
counter
outer_function()
Summary
- Global scope: Variables defined outside any function, accessible throughout the entire program.
- Local scope: Variables defined within a function, accessible only inside that function.
- Enclosing scope: Variables in an outer function are accessible to inner functions, but modifications require
.nonlocal
- Global keyword: Used to modify a global variable within a function.
- Nonlocal keyword: Used to modify a variable in an enclosing (outer) function from an inner function.