In Python, the keywords global
and nonlocal
are used when dealing with variable scope. In other words, they help determine where a variable is located when you access or modify it.
1. Scope Refresher
Before we jump in, remember that scope refers to the part of a program where a variable is accessible.
- Local scope: Inside a function
- Global scope: Outside all functions
- Enclosing scope: A function inside another function
Here's a visual diagram to help you understand variable scopes:
2.The global Keyword
The global keyword is used to modify a variable outside of the current function, specifically the one in the global scope.
Normally, assigning to a variable inside a function creates a local variable. If you want to change a variable that exists at the global(module) level, you need to declare it global.
Example 1:
x = 10
def change_global():
global x
x = 20
change_global()
print(x) # Output: 20
Example 2:
counter = 0
def increment():
global counter
for _ in range(5):
counter += 1
increment()
print(counter) # Output: 5
Example 3:
flag = False
def activate():
global flag
flag = True
activate()
print(flag) # Output: True
What's happening here?
Even though x, counter, or flag were defined outside the function, we can change their values inside the function using global. Without the global keyword, Python would treat them as new local variables.
3. The nonlocal Keyword
The nonlocal keyword is used in nested functions. It allows you to modify a variable in the enclosing (but not global) scope. This is useful when you want to update a variable in an outer function from within an inner function.
Example 1:
def outer():
y = 5
def inner():
nonlocal y
y = 10
inner()
print(y) # Output: 10
outer()
Example 2:
def outer():
msg = "Hello"
def inner():
nonlocal msg
msg += ", World!"
inner()
print(msg) # Output: Hello, World!
outer()
Example 3:
def counter_maker():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
c = counter_maker()
print(c()) # Output: 1
print(c()) # Output: 2
What's happening here?
In all of these examples, the inner function modifies a variable in the outer function using nonlocal. This would not be possible without declaring the variable as nonlocal.
Comments
Post a Comment