Global variables across Python modules

The best way to share global variables across different modules within the same program is to create a special module (often named config or cfg). Import the config module in all modules of your application; the module then becomes available as a global name. There is only one instance of each module, and so any changes made to the module object get reflected everywhere. For Example, sharing global variables across modules.

Code 1: Create a config.py file to store global variables

Python3




x = 0
y = 0
z = "none"


Code 2: Create a modify.py file to modify global variables

Python3




import config
config.x = 1
config.y = 2
config.z = "w3wiki"


Here we have modified the value of x, y, and z. These variables were defined in the module config.py, hence we have to import config module, and can use config.variable_name to access these variables.

Create a main.py file to modify global variables

Python3




import config
import modify
print(config.x)
print(config.y)
print(config.z)


Output:

1
2
w3wiki

Global keyword in Python

In this article, we will cover the global keyword, the basic rules for global keywords in Python, the difference between the local, and global variables, and examples of global keywords in Python.

Similar Reads

What is the purpose of global keywords in python?

A global keyword is a keyword that allows a user to modify a variable outside the current scope. It is used to create global variables in Python from a non-global scope, i.e. inside a function. Global keyword is used inside a function only when we want to do assignments or when we want to change a variable. Global is not needed for printing and accessing....

Global keyword in the python example

Example 1: Accessing global Variable From Inside a Function...

Modifying global Mutable Objects

...

Global variables across Python modules

...

Global in Nested functions

...

Contact Us