How do I share global variables across modules in Python?


To share global variable across module in Python, let us first understand what are global variables and its scope.

Global Variable

Example

If a variable is accessible from anywhere i.e. inside and even outside the function, it is called a Global Scope. Let’s see an example −

# Variable i = 10 # Function def example(): print(i) print(i) # The same variable accessible outside the function # Calling the example() function example() # The same variable accessible outside print(i)

Output

10
10
10

Share Information Across Modules

Now, to share information across modules within a single program in Python, we need to create a config or cfg module. To form it as a global i.e. a global variable accessible from everywhere as shown in the above example, just import the config module in all modules of your application −

import config

By importing the module in all the modules, the module then becomes available as a global name. Since there is only one instance of each module, any changes made to the module object get reflected everywhere.

Let us now see an example. Here’s config.py

# Default value of the 'k' configuration setting k = 0

Here’s mod.py. This imports the above config:

import config config.k = 1

Here’s main.py. This imports bode config and mod:

import config import mod print(config.k)

Updated on: 19-Sep-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements