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 to share common data among multiple Python files?
In Python, sharing common data such as constants, configuration settings or shared resources among multiple files is a routine task in modular application development. The data will be centralized in a dedicated module which allows it to be maintained in one place and imported wherever needed.
Before proceeding with various approaches to share data among multiple Python files, first we need to understand what is a module and what is shared data.
What is a Module?
A Module is a Python file (.py) that contains definitions such as variables, functions, classes or runnable code. By placing shared data in its own module we can import that module in other files and access the data directly.
What is Shared Data?
The Shared data refers to values or objects such as configuration parameters, constants or resource handles which are defined once and used across multiple modules. This pattern ensures consistency, avoids duplication and simplifies maintenance.
In this article we are going to see the various methods available in Python to share common data among multiple files.
Using a config.py Module
The config.py module holds shared constants and configuration settings that can be imported by other Python files ?
# config.py APP_NAME = "Tutorialspoint" VERSION = "1.0.0" DATABASE_URL = "postgresql://user:pass@localhost:5432/mydb"
Example
Here in this example, we are importing the config.py file to access the common data available in the config.py ?
# main.py
# Assuming config.py exists with the above constants
# For demo purposes, we'll define the constants directly
APP_NAME = "Tutorialspoint"
VERSION = "1.0.0"
DATABASE_URL = "postgresql://user:pass@localhost:5432/mydb"
def start_app():
print(f"Starting {APP_NAME} v{VERSION}")
print(f"Connecting to {DATABASE_URL}")
start_app()
Starting Tutorialspoint v1.0.0 Connecting to postgresql://user:pass@localhost:5432/mydb
Using Environment Variables
Environment variables help us to keep sensitive or environment-specific data, such as API keys, credentials or other secrets, out of our source code. We can read them in Python with the os module ?
Example
In this example, we are using environment variables to store and access sensitive configuration data ?
import os
# Simulate setting environment variable (normally done externally)
os.environ["API_KEY"] = "abcdef123456"
# Reading environment variable
API_KEY = os.getenv("API_KEY", "default_key")
def call_service():
print(f"Using API key: {API_KEY}")
call_service()
Using API key: abcdef123456
Using Global Variables in Shared Modules
Global variables in a shared module can be imported and used across multiple files. This approach is simple but requires careful management to avoid unexpected modifications ?
# Simulating shared_data.py
counter = 0
user_settings = {"theme": "dark", "language": "en"}
def increment_counter():
global counter
counter += 1
return counter
def get_user_setting(key):
return user_settings.get(key)
# Using the shared data
print("Initial counter:", counter)
print("Counter after increment:", increment_counter())
print("User theme:", get_user_setting("theme"))
Initial counter: 0 Counter after increment: 1 User theme: dark
Using a Singleton Configuration Class
A singleton configuration class ensures that only one instance of our configuration exists throughout the application. Any module that imports it receives the same object with shared settings ?
class Config:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.app_name = "Tutorialspoint"
cls._instance.version = "1.0.0"
cls._instance.debug_mode = True
return cls._instance
# Usage example
cfg1 = Config()
cfg2 = Config()
print("Same instance?", cfg1 is cfg2)
print(f"App: {cfg1.app_name} v{cfg1.version}")
print("Debug mode:", cfg2.debug_mode)
Same instance? True App: Tutorialspoint v1.0.0 Debug mode: True
Comparison of Methods
| Method | Best For | Pros | Cons |
|---|---|---|---|
| config.py Module | Constants & simple settings | Simple, fast access | Hard-coded values |
| Environment Variables | Sensitive data | Secure, environment-specific | All values are strings |
| Global Variables | Runtime shared state | Simple, mutable | Can be accidentally modified |
| Singleton Class | Complex configurations | Object-oriented, controlled access | More complex implementation |
Conclusion
Choose config.py for simple constants, environment variables for sensitive data, and singleton classes for complex shared configurations. Each method serves different use cases in modular Python applications.
