Using global variables across multiple files in Python

This trivial guide is about using global variables across multiple files in Python. But before getting into the topic, let's briefly look at global variables and their purpose across multiple files.
Global variables in Python

A global variable is a variable that does not belong to the scope of a function and can be used throughout the program. This shows that global variables can also be used inside or outside the function body.

Let's look at an example:

x = "my global var"
def fun1():
    print("Inside fun1(): ",x)
fun1()
print("In global context: ",x)

In this code we define a global variable x and assign some value to it. We then printed the x variable inside and outside the function to see the values ​​in both ranges.

Output:
insert image description here
The output shows that the value of the variable is the same inside and outside the function. If we need to change the value of a global variable in some local scope, such as in a function, then we need to use the keyword global when declaring the variable.

Using global variables across multiple files

If our program uses multiple files, and these files need to update variables, then we should declare variables with the global keyword like this:

global x = "My global var"

Consider an example where we have to deal with multiple files of Python code and a global variable for a list of students. The resource.py file has a global list of students, and prog.py has a method that appends students to this global list.

We can implement this concept with the following code:

code-resource.py:

def initialize():
    global students
    students = []

code-prog.py:

import resource
def addStudent():
    resource.students.append('John')
    resource.students.append('Dave')

Code-Main.py:

#Python小白学习交流群:711312441
import resource
import prog
resource.initialize()
prog.addStudent()
print(resource.students[0])
print(resource.students[1])

In the first resource.py file, we define a function where we declare a list studentList and initialize it to an empty list. In the next file (ie prog.py) we include the resource module and then define a function addStudent in which we append two objects to the global list studentList.

In the main file Main.py, we include two modules, resource and prog. Later, we called the functions initialize and addStudent of these two modules respectively.

Afterwards, when we print the list index, we get the following output:
insert image description here
Therefore, we can use the global keyword to define a global variable in one Python file for use in other files. Now, to access the global variables of one file in another file, import the file with global variables as a module of another file, and directly access any global variables of the imported module without additional complicated operations.

Guess you like

Origin blog.csdn.net/qdPython/article/details/131998855