Demystifying Python Scripts, Modules, and Packages
Section 1: Scripts v.s. Modules
They look common since
- Both being Python files with
.pyextensions. - Both contain Python definitions (classes, functions, variables) and statements.
They are essentially different. If you search online, you can find many sources defining their use as below:
Think: Is hello.py below a Python module or script?
print("hello, you are running a python code")Section 2: Python Modules
Why do we need it? Simply speaking, it enables code reuse with better readability and maintainability.
For example, as a machine learning engineer, you commonly implement many models (e.g., Model-A, Model-B, Model-C) and metrics (e.g., Metric-A, Metric-B, Metric-C). Without Python module, you implement all the metrics for all the models.
- Readability: The duplication challenges you for reading the code
- Maintainability: It also challenges you for maintaining the code.
For example, if you put the incorrect code below in the 3 model files to calculate the mean square error (MSE), you have to go to 3 files to correct the mistake.
difference = actual - predicted
mse = difference.mean()In constrast, if you save the mean square error (MSE) function in a Python module, you only need to change the function once.
Get Xinzhe Li, PhD in Language Intelligence’s stories in your inbox
Join Medium for free to get updates from this writer.
To do this, you can create a module named metrics.py that contains the MSE function. This way, you can simply import the MSE function from your metrics module whenever you need to evaluate a regression model. Here is how you could define the MSE function within the metrics.py module:
def mean_square_error(actual, predicted):
"""
Calculate the mean square error between actual and predicted values.
Parameters:
actual (list or numpy array): The actual values.
predicted (list or numpy array): The predicted values.
Returns:
float: The mean square error.
"""
difference = actual - predicted
squared_difference = difference ** 2
mse = squared_difference.mean()
return mseThen, in your script or any other module where you want to use the MSE function, you can import it and use it as follows:
from metrics import mean_square_error
# Example actual and predicted values
actual = [3, 5, 2.5, 6]
predicted = [2.5, 5.0, 2.0, 8]
# Calculate MSE
mse = mean_square_error(actual, predicted)
print(f"Mean Square Error: {mse}")(Optional) What if you have different packages providing the same function. Python allows the same function names to be used in different modules without conflict. For instance, the mean_square_error function you've defined in your metrics.py module can coexist with the mean_squared_error function available in the popular machine learning library, Scikit-learn (sklearn.metrics). Thanks to Python's namespace management, when you import these functions into your scripts, you can distinguish between them by prefixing them with the module name. For example, you could use your custom mean_square_error for certain tasks and sklearn.metrics.mean_squared_error for others, without any naming conflict. This is achieved by importing them like so:
from metrics import mean_square_error as mse_custom
from sklearn.metrics import mean_squared_error as mse_sklearn
# Example usage of your custom MSE
actual = [3, 5, 2.5, 6]
predicted = [2.5, 5.0, 2.0, 8]
mse_custom_result = mse_custom(actual, predicted)
print(f"Custom MSE: {mse_custom_result}")
# Example usage of Scikit-learn's MSE
mse_sklearn_result = mse_sklearn(actual, predicted)
print(f"Scikit-learn MSE: {mse_sklearn_result}")Section 3: Python Package
Package structures Python modules. Normally, the presence of __init__.py files in each directory of a Python package is what distinguishes a package from a mere folder or directory.
Note: Before Python 3.3,
__init__.pyfile is used for Python interpretor to recognize directories as packages, allowing its modules to be imported. Now, it is not necessary.
A Practical Example
Here is a practical machine learning package I devised called ml. Within this package, we have two subpackages: models and evaluation
ml/
models/
__init__.py
fully_connected_layer.py
regression.py
python_script.pyHere is the content of the module fully_connected_layer.py .
class FullyConnectedLayer:
"""Fully connected layer class for neural network model"""
def __init__(self, learning_rate=0.01):
self.learning_rate = learning_rate
self.weights = None
self.bias = None
self.input_shape = None
self.output_shape = None
def forward(self, inputs):
"""Forward pass of the fully connected layer"""
return inputs @ self.weights + self.biasAssess Python Definitions in A Modules:
- we use “dotted module names” to access Python’s module namespace by chaining the package and subpackages/modules (
from package.module import itemwhereitemcan be a function, a class, a variable or subpackage), e.g., fromml.models.fully_connected_layer import FullyConnectedLayeras below.
# code in the python_script.py
from ml.models.fully_connected_layer import FullyConnectedLayer
model = FullyConnectedLayer()- Or we can use the pattern like
from package import moduleand then use module to access the classes, functions and variables.
# code in python_script.py
from ml.models import fully_connected_layer
model = fully_connected_layer.FullyConnectedLayer()- Modifying
__init__.pyFiles for Direct Access: To directly accessFullyConnectedLayerclass from themodelssubpackage, modify the__init__.pyfiles as follows:ml/models/__init__.py:
from .models.fully_connected_layer import FullyConnectedLayerNow, users of your ml package can import the LinearRegression class and the mean_squared_error function directly from the package, without having to navigate through the subpackage structure:
# code in pytho_script.py
from ml import FullyConnectedLayerSection 4: Using Public Packages
To leverage the vast ecosystem of Python for data science and machine learning projects, you’ll likely need to install several key public packages. These packages provide a wide range of functionalities, from matrix manipulation to advanced machine learning algorithms and data visualization.
pip install numpy # Numpy for matrix manipulation
pip install scipy # SciPy for statistic optimization and functions
pip install pandas # pandas for reading data (Dealing with data as Numpy matrix)
pip install scikit-learn # Sklearn for API call of ML algorithms
pip install matplotlib # Matplotlib for visualizationInstead of executing each pip install command separately, you can streamline the process by specifying all required packages in a single file named requirements.txt. This file lists each package (and optionally, the desired version) on a separate line. To install all the packages listed in requirements.txt, run the following command:
pip install -r requirements.txtThis approach not only saves time but also ensures consistency across different environments, making it easier to manage dependencies for projects.
Section 5: Can We … ?
Can We Directly Run A Module?
If we directly run the code in regression.py , an import error occurs: ImportError: attempted relative import with no known parent package . Because regression.py is used as a Python script, while the relative import via dots should be used between modules within a package.
# code in ml/models/regression.py
import numpy as np
from ..metrics import mean_squared_error, r2_score, variance_in_cv_scoresdef ols_estimate_for_linear_regression(X, Y): # Mean of X and Y
X_mean = np.mean(X)
Y_mean = np.mean(Y) # Calculate beta_1 (slope)
beta_1 = np.sum((X - X_mean) * (Y - Y_mean)) / np.sum((X - X_mean) ** 2) # Calculate beta_0 (intercept)
beta_0 = Y_mean - beta_1 * X_mean return beta_0, beta_1if __file__ == "__main__":
import pandas as pd
df = pd.read_csv("data/house-prices/train.csv") # from https://www.kaggle.com/competitions/house-prices-advanced-regression-techniques/data
x = df['GrLivArea'] # Above grade (ground) living area square feet
y = df['SalePrice']
beta_0, beta_1 = ols_estimate_for_linear_regression(x, y)
predictions = beta_0 + beta_1 * x
error = mean_squared_error(y, predictions)
To run this successfully, we have to tell Python interpreter that it works as a Python module within the ml library. You can use python -m command, e.g., python -m my_ml_package.models.regression .
Can We Run A Notebook inside A Python Package?
Yes. But you have to manually add the parent directory of the package into sys.path so that the Python import system can find the package.










