![]()
In Python, the global and nonlocal keywords are used to manage variable scope and allow you to modify variables in different namespaces (global and nonlocal). These keywords are essential for controlling how and where variables are accessed and modified within your programs.
1. The global Keyword
The global keyword allows you to modify variables declared outside the current function scope, i.e., variables defined at the global level. When a variable is declared as global inside a function, any assignment to that variable will affect the variable in the global scope.
When to Use global:
- When you need to change the value of a global variable from within a function.
- To avoid creating a new local variable with the same name as a global variable.
Example: Using global Keyword
x = 10 # Global variable
def modify_global():
global x # Refers to the global variable x
x = 20 # Modifies the global variable
modify_global()
print(x) # Output: 20
Explanation:
global xtells Python that thexinside the function refers to the global variablex.- Without the
globalkeyword, a new local variablexwould be created, and the globalxwould remain unchanged.
2. The nonlocal Keyword
The nonlocal keyword is used to modify variables in the nearest enclosing scope that is not global. This is commonly used when working with nested functions, where a variable in the enclosing function needs to be modified by an inner function.
When to Use nonlocal:
- When you need to modify a variable in an enclosing scope (but not global) within a nested function.
- It allows inner functions to update variables in the nearest enclosing scope, such as in closures.
Example: Using nonlocal Keyword
def outer_function():
x = 10 # Variable in the enclosing scope
def inner_function():
nonlocal x # Refers to the variable x in the enclosing scope
x = 20 # Modifies the variable x in the enclosing scope
inner_function()
print(x) # Output: 20
outer_function()
Explanation:
nonlocal xtells Python that the variablexshould refer to thexin the nearest enclosing scope (the scope ofouter_function), not a local variable insideinner_function.- Without
nonlocal,inner_functionwould create a new local variablex, leaving the variablexin theouter_functionunchanged.
3. Key Differences Between global and nonlocal
| Feature | global | nonlocal |
|---|---|---|
| Scope of Variable | Refers to variables in the global scope. | Refers to variables in the nearest enclosing function scope. |
| Modifying Variables | Allows modification of variables at the global level. | Allows modification of variables in the enclosing (non-global) scope. |
| Usage Context | Used for global variables in a function. | Used for variables in nested functions (enclosing scopes). |
| Cannot be Used in | Local variables or parameters inside functions. | Global variables. |
4. Why Use global and nonlocal?
global: Useful for scenarios where you want to modify a global variable, such as configuration values or counters that should persist across function calls. However, it can lead to unintentional side effects if used excessively, so it should be used sparingly.nonlocal: Essential for modifying variables within nested functions or closures. It enables inner functions to modify variables in outer functions without needing to use global variables.
5. Example: Both global and nonlocal in Action
Here is an example that demonstrates how both global and nonlocal work in a program:
x = 5 # Global variable
def outer_function():
x = 10 # Variable in the outer function
def inner_function():
nonlocal x # Modify the x from outer_function
x = 15
def inner_most_function():
global x # Modify the global x
x = 20
inner_most_function()
print(f"Inner function modified x to: {x}") # Output: 15
inner_function()
print(f"Outer function modified x to: {x}") # Output: 15
print(f"Global x before: {x}") # Output: 5
outer_function()
print(f"Global x after: {x}") # Output: 20
Explanation:
- Global variable
xis initially set to5. outer_functionhas its ownx, which is set to10.inner_functionmodifiesxfromouter_functionusingnonlocal, setting it to15.inner_most_functionmodifies the globalxusingglobal, setting it to20.- After running the functions, the final value of
xin the global scope is20.
6. Use Cases for global and nonlocal
Use Case 1: Modifying a Global Counter
counter = 0 # Global counter
def increment_counter():
global counter
counter += 1
print(f"Counter is: {counter}")
increment_counter() # Output: Counter is: 1
increment_counter() # Output: Counter is: 2
Use Case 2: Using nonlocal in Closures
def outer():
x = 10 # Local variable in outer function
def inner():
nonlocal x
x += 5 # Modifies the x variable in outer
print(f"Value of x in inner: {x}")
inner() # Output: Value of x in inner: 15
print(f"Value of x in outer: {x}") # Output: Value of x in outer: 15
outer()
