 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
