How to share common data among multiple Python files?


In the domain of Python programming, organization and modularity are pivotal in crafting efficient and maintainable code. As your Python projects grow in complexity, the necessity to disseminate common data across multiple files becomes paramount. Gratefully, Python furnishes several techniques to accomplish this seamlessly. Within this article, we shall embark on a journey of a few distinct methods to share common data among multiple Python files. Each approach boasts its unique strengths and adaptability, endowing you with the ability to construct scalable and robust Python projects. You will be guided through each method with comprehensive explanations in a human-friendly style. By the article's conclusion, you shall be equipped with the know-how to unify your Python files and harmonize data sharing with elegance. Let us take a deep dive into the realm of Python modularity!

Understanding Data Sharing in Python

Before immersing ourselves in the code examples, let us briefly comprehend the significance of sharing common data in Python. Data sharing avails you in avoiding information duplication, and foster code organization, and maintainability. Centralizing data in one repository empowers facile modification, access, and updates across multiple Python files.

Utilizing Global Variables

Our inaugural example explains data sharing through global variables, granting accessibility across multiple Python files.

Example

file1.py

# file1.py
shared_data = "Hello from file1.py!"


file2.py

# file2.py
from file1 import shared_data
print(shared_data)

In this example, we establish a global variable shared_data in file1.py, embodying the message "Hello from file1.py!". In file2.py, we import the shared_data variable from file1.py utilizing the from ... import ... syntax. Thus, the shared_data variable becomes accessible in file2.py, empowering us to print the message to the console.

If you run the above code, we get

Output

Hello from file1.py!

Utilizing a Configuration File

Our second approach showcases data sharing via a configuration file, serving as a central repository for shared data.

Example

config.py

# config.py
shared_data = "Hello from config.py!"


file.py

# file.py
from config import shared_data

print(shared_data)

In this example, we create a distinct file config.py, containing the global variable shared_data. Subsequently, we import the shared_data variable from config.py into the file.py script. This technique centralizes shared data within a dedicated configuration file, simplifying management and updates. If above code is run we get.

Output

Hello from config.py!

Leveraging a Class

Our third method exemplifies data sharing through a Python class, encapsulating data and functionality for facile access.

data_manager.py

Example

# data_manager.py
class DataManager:
   def __init__(self):
     self.shared_data = "Hello from DataManager!"


# Instantiate the DataManager class
data_manager = DataManager()


file.py

# file.py
from data_manager import data_manager

print(data_manager.shared_data)

If you run the above code, the following was the output

Output

Hello from DataManager!

In this example, we define a class DataManager in data_manager.py, encompassing the shared data as an instance variable. An instance of the DataManager class is created and stored in the data_manager variable. In file.py, we import the data_manager variable and access the shared data using dot notation.

Using a Dictionary

Our fourth example showcases data sharing using a Python dictionary, enabling access to key-value pairs across multiple files.

shared_data.py

Example

# shared_data.py

shared_data = {"greeting": "Hello", "target": "world"}


file.py

# file.py
from shared_data import shared_data

print(shared_data["greeting"], shared_data["target"])

If the above code is run, we get the following output

Output

Hello world

In this example, we define a dictionary shared_data in shared_data.py, embodying key-value pairs for greeting and target. In file.py, we import the shared_data dictionary and access its values using keys to print the greeting message "Hello world".

Employing a Custom Module

Our final endeavor epitomizes data sharing through a custom Python module, encapsulating related data and functions.

utils.py

Example

# utils.py
shared_variable = 42

def shared_function():
   return "Hello from shared_function!"


file.py

# file.py
import utils

print(utils.shared_variable)
print(utils.shared_function())

If the above code is run, we get the following output

Output

42
Hello from shared_function!

In this example, we craft a custom module utils.py, encompassing a shared variable shared_variable and a shared function shared_function(). In file.py, we import the utils module and access the shared data and function.

In conclusion, sharing common data among multiple Python files is an integral facet of engendering modular and maintainable code. Within this article, we traversed five diverse methods to achieve this, each possessing unique strengths catering to specific needs and coding styles.

Whether you gravitate towards global variables, a configuration file, Python classes, dictionaries, or custom modules, each method bestows the ability to centralize data and streamline access across multiple Python files.

As you proceed on your Python journey, realize the potency of data sharing to cultivate scalable and organized Python projects. Hopefully, these data-sharing techniques elevate your Python skills and pave the way for proficient and resilient code.

Updated on: 03-Aug-2023

822 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements