Global Variables in Python

Global Variables in Python

Global variables are module-level variables. These kinds of variables are not only accessible but also can be modified from every part of the module that includes methods, classes, and their methods.

Every programming language contains global variables, and in this article, we will specifically talk about global variables in Python.

Use the Global Variables in Python

The module-level variables can be used and modified inside methods, classes, and their methods with the help of the global keyword. By default, module-level variables inside methods can only be accessed, etc.

To modify them, we have to use the global keyword. This function uses the following syntax.

global <comma separated varialbes>

Variables placed next to the global variables can be safely modified. Let us understand this with the help of a relevant example.

x = 10

def modify():
    global x, y, z
    print("X:", x)
    x += 20
    print("X:", x)
    print("Y:", y)
    y += 200
    print("Y:", y)
    print("Z:", z)
    z += 1000
    print("Z:", z)
    
y = 100
z = 1000
modify()

Output:

X: 10
X: 30
Y: 100
Y: 300
Z: 1000
Z: 2000

As we can see, to access x, y, and z, the global keyword in Python was used. Without this statement, the Python interpreter will throw an UnboundLocalError: local variablereferenced before error.

Additionally, note that all these variables are declared above the function call to the hello() method. It is an essential detail that one should keep in mind while working with global variables.

Always use variables declared and defined before the function call.

If a variable is declared and determined after the function call is used inside the function, the Python interpreter will throw a NameError.

The following Python code depicts a similar situation.

x = 10

def modify():
    global x, z
    print("X:", x)
    x += 20
    print("X:", x)
    print("Z:", z)
    z += 1000
    print("Z:", z)
    
modify()
z = 1000

Output:

X: 10
X: 30
Traceback (most recent call last):
  File "main.py", line 12, in <module>
    modify()
  File "main.py", line 8, in modify
    print("Z:", z)
NameError: name 'z' is not defined

Generally, it is recommended not to use global variables because they can lead to unexpected bugs that become hard to debug.

In some cases, since many methods or code pieces start depending upon them, even a single unnecessary manipulation can lead to some serious bugs.

We are not trying to discourage their usage, but one should keep track of every statement that aims to manipulate the global variables.

Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

LinkedIn GitHub