Global keyword in Python
The global keyword in Python allows a function to modify variables that are defined outside its scope, making them accessible globally. Without it, variables inside a function are treated as local by default. It's commonly used when we need to update the value of a global variable within a function, ensuring the changes persist outside the function.
Example:
x = 10 # global variable
def fun():
global x # referencing the global variable x
x = 20 # modifying the global variable
fun()
print(x)
Output
20
Explanation: This code uses the global keyword inside the function to modify the global variable x. By calling fun(), the global x is updated to 20 .
Examples of using the global keyword
Example 1: Accessing global Variable From Inside a Function
# global variables
a = 15
b = 10
# function to perform addition
def add():
c = a + b # accessing global variables
print(c)
# calling the function
add()
Output:
25
Explanation: In this example, the global variables a and b are accessed inside the function without needing the global keyword because we are just referencing them.
Example 2: Modifying Global Variable From Inside the Function
a = 15 # global variable
# function to change a global value
def change():
# increment value of a by 5
b = a + 5
a = b
print(a)
change()
Output:
UnboundLocalError: local variable 'a' referenced before assignment
Explanation: Here, Python assumes a is a local variable inside the function since we try to assign a value to it. To modify the global a, we need to use the global keyword.
Example 3: Changing Global Variable using global
x = 15 # global variable
def change():
# using a global keyword
global x
# increment value of a by 5
x = x + 5
print(x)
change()
print(x)
Output
20 20
Explanation: In this example, we first define x as a global keyword inside the function change(). The value of x is then incremented by 5, i.e. x=x+5 and hence we get the output as 20. As we can see by changing the value inside the function change(), the change is also reflected in the value outside the global variable.
Modifying global Mutable Objects
Unlike immutable objects (e.g., integers, strings), mutable objects (e.g., lists, dictionaries) can be modified without needing the global keyword.
Example 1: Modifying list elements without using global keyword.
Here, we can modify list elements defined in global scope without using global keyword. Because we are not modifying the object associated with the variable a, but we are modifying the items the list contains. Since lists are mutable data structures, thus we can modify its contents.
a = [10, 20, 30]
def fun():
for i in range(len(a)):
a[i] += 10
print("before", a)
fun()
print("after", a)
Output
before [10, 20, 30] after [20, 30, 40]
Example 2: Modifying list variable using global keyword.
Here we are trying to assign a new list to the global variable. Thus, we need to use the global keyword as a new object is created. Here, if we don't use the global keyword, then a new local variable a will be created with the new list elements. But the global variable arr will be unchanged.
a = [10, 20, 30]
def fun():
global a
a = [20, 30, 40]
print("before", a)
fun()
print("after", a)
Output
before [10, 20, 30] after [20, 30, 40]
Global variables across Python modules
global keyword is also useful when we need to share global variables between different Python modules. We can define a separate configuration module to hold global variables and import them into other modules.
Code 1: config.py for Storing Global Variables
# config.py
x = 0
y = 0
z = "none"
Code 2: modify.py to Modify Global Variables
# modify.py
import config
config.x = 1
config.y = 2
config.z = "geeksforgeeks"
Code 3: main.py to Access Modified Global Variables
# main.py
import config
import modify
print(config.x)
print(config.y)
print(config.z)
Output:
1
2
geeksforgeeks
Explanation : In this example, the variables x, y, and z are defined in config.py, modified in modify.py, and then accessed in main.py. This is an efficient way to share global variables across different modules.
Global in Nested functions
In order to use global inside a nested function, we have to declare a variable with a global keyword inside a nested function
def add():
x = 15
def change():
global x # Declare x as global to modify it inside the nested function
x = 20
print("Before changing:", x)
print("Making change")
change()
print("After changing:", x)
add()
print("Value of x outside:", x)
Output
Before changing: 15 Making change After changing: 15 Value of x outside: 20
Explanation: In this example, the outer function add has a local variable x. The nested function change modifies the global x. The changes to x are reflected outside the function.