Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I share global variables across modules in Python?
To share global variables across modules in Python, you need to understand global variable scope and create a shared configuration module. This approach allows multiple modules to access and modify the same variables.
Global Variable Scope
A global variable is accessible from anywhere in the program both inside and outside functions. Here's how global variables work ?
# Global variable
counter = 10
# Function accessing global variable
def display_counter():
print(counter)
# Accessing global variable outside function
print(counter)
# Calling the function
display_counter()
# Accessing global variable again
print(counter)
10 10 10
Creating a Configuration Module
To share variables across modules, create a dedicated configuration module. Import this module in all files that need access to the shared variables.
Step 1: Create config.py
# config.py - Shared configuration module database_url = "localhost:5432" max_connections = 100 debug_mode = False
Step 2: Use Variables in Different Modules
Here's database.py that modifies the shared variables ?
# database.py
import config
def initialize_database():
config.max_connections = 50
config.debug_mode = True
print(f"Database initialized with {config.max_connections} connections")
Here's main.py that imports both modules ?
# main.py
import config
import database
# Check initial values
print(f"Initial connections: {config.max_connections}")
print(f"Debug mode: {config.debug_mode}")
# Modify values in database module
database.initialize_database()
# Check modified values
print(f"Updated connections: {config.max_connections}")
print(f"Debug mode: {config.debug_mode}")
Complete Working Example
Here's a simplified example you can run to see how it works ?
# Simulating config.py content
class Config:
counter = 0
message = "Hello"
config = Config()
# Simulating module1.py function
def increment_counter():
config.counter += 1
config.message = "Updated"
# Simulating module2.py function
def display_values():
print(f"Counter: {config.counter}")
print(f"Message: {config.message}")
# Main program
print("Initial values:")
display_values()
print("\nAfter incrementing:")
increment_counter()
display_values()
print("\nAfter another increment:")
increment_counter()
display_values()
Initial values: Counter: 0 Message: Hello After incrementing: Counter: 1 Message: Updated After another increment: Counter: 2 Message: Updated
How It Works
Python creates only one instance of each imported module. When you import the same module in different files, they all reference the same module object. Any changes made to module attributes are reflected everywhere the module is imported.
Best Practices
- Use descriptive names for your configuration module (config.py, settings.py, globals.py)
- Initialize variables with sensible default values
- Document which variables are meant to be modified by other modules
- Avoid modifying built-in modules or third-party library modules
Conclusion
Create a dedicated configuration module and import it across all modules that need shared variables. Since Python maintains only one instance per module, changes are automatically reflected everywhere the module is imported.
