Understanding Python modules, packages, and imports
Author
Mohammed Adil Siraju
Published
September 18, 2025
What are Modules?
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py added.
# Example: Using built-in modulesimport mathimport datetime# Using math moduleprint(f"Pi value: {math.pi}")print(f"Square root of 16: {math.sqrt(16)}")# Using datetime modulenow = datetime.datetime.now()print(f"Current time: {now}")
Pi value: 3.141592653589793
Square root of 16: 4.0
Current time: 2025-09-18 11:56:02.592034
Import Statements
There are several ways to import modules in Python:
# 1. Import entire moduleimport numpy# 2. Import with aliasimport numpy as np# 3. Import specific functionsfrom math import sqrt, pi# 4. Import all (not recommended)# from math import *# Examplesarr = np.array([1, 2, 3, 4, 5])print(f"Array: {arr}")print(f"Mean: {np.mean(arr)}")print(f"Using imported sqrt: {sqrt(25)}")print(f"Using imported pi: {pi}")
Array: [1 2 3 4 5]
Mean: 3.0
Using imported sqrt: 5.0
Using imported pi: 3.141592653589793
Creating Custom Modules
You can create your own modules by saving Python code in a .py file.
# Example: Creating a simple utility module (conceptually)# This would be saved as utils.pydef greet(name):"""Greet a person by name"""returnf"Hello, {name}!"def calculate_area(radius):"""Calculate area of a circle"""import mathreturn math.pi * radius **2# ConstantsVERSION ="1.0.0"AUTHOR ="Mohammed Adil Siraju"# Test the functionsprint(greet("Adil"))print(f"Area of circle with radius 5: {calculate_area(5):.2f}")print(f"Module version: {VERSION}")
Hello, Adil!
Area of circle with radius 5: 78.54
Module version: 1.0.0
Packages
A package is a collection of modules organized in directories. Packages help organize related modules together.
# Example package structure:# mypackage/# __init__.py# module1.py# module2.py# subpackage/# __init__.py# submodule.py# Importing from packages# import mypackage.module1# from mypackage import module2# from mypackage.subpackage import submoduleprint("Package structure example shown above")
Package structure example shown above
Popular Python Packages for Data Science
Let’s explore some essential packages for AI/ML work:
# Data manipulation and analysisimport pandas as pdimport numpy as np# Visualizationimport matplotlib.pyplot as pltimport seaborn as sns# Machine Learningfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import mean_squared_error# Create sample datadata = {'x': [1, 2, 3, 4, 5],'y': [2, 4, 6, 8, 10]}df = pd.DataFrame(data)print("Sample DataFrame:")print(df)# Simple linear regression exampleX = df[['x']]y = df['y']model = LinearRegression()model.fit(X, y)predictions = model.predict(X)mse = mean_squared_error(y, predictions)print(f"\nLinear Regression Results:")print(f"Slope: {model.coef_[0]:.2f}")print(f"Intercept: {model.intercept_:.2f}")print(f"MSE: {mse:.2f}")
Sample DataFrame:
x y
0 1 2
1 2 4
2 3 6
3 4 8
4 5 10
Linear Regression Results:
Slope: 2.00
Intercept: -0.00
MSE: 0.00
Best Practices
Use descriptive names for modules and packages
Keep modules focused on a single responsibility
Use __init__.py to control package imports
Document your modules with docstrings
Follow PEP 8 naming conventions
Avoid circular imports
Key Takeaways
Modules help organize and reuse code
Packages group related modules together
Import statements control what code is available
Python’s standard library provides many useful modules
Third-party packages extend Python’s capabilities
Next: We’ll explore Python functions and classes in detail.