
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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)
- Related Articles
- How do I declare global variables on Android?
- Explain the visibility of global variables in imported modules in Python?
- How do I declare global variables on Android using Kotlin?
- How do I declare a global variable in Python class?
- How do I get IntelliJ to recognize common Python modules?
- How do Python modules work?
- Global and Local Variables in Python?
- Global vs Local variables in Python
- Why we do not have global variables in C#?
- Global variables in Java
- How to Share Session ID across Different Requests in Postman?
- How to declare global variables in Android?
- How to declare global Variables in JavaScript?
- How to use global variables in Ruby?
- How to use Global Variables in JavaScript?
