Modules and packages are essential concepts in Python programming that
allow developers to organize code efficiently, enhance reusability, and
improve maintainability. In this class, we will explore the basics of modules
and packages, how to create and use them, and their significance in larger
projects.
Modules in Python
What is a Module?
A module is a single file containing Python code. It can include functions,
classes, and variables. Modules help in logically organizing code, making it
reusable across different programs.
Example: Creating and Using a Module
1. Create a Module:
Create a file named math_utils.py and add the following code:
# math_utils.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
2. Use the Module in Another Script:
Create a file named main.py and use the math_utils module:
# main.py
import math_utils
result_add = math_utils.add(5, 3)
result_subtract = math_utils.subtract(5, 3)
print(f"Addition: {result_add}") # Output: Addition: 8
print(f"Subtraction: {result_subtract}") # Output: Subtraction: 2
○
3. Importing Specific Functions:
You can import specific functions from a module:
# main.py
from math_utils import add, subtract
result_add = add(5, 3)
result_subtract = subtract(5, 3)
print(f"Addition: {result_add}") # Output: Addition: 8
print(f"Subtraction: {result_subtract}") # Output: Subtraction: 2
Packages in Python
What is a Package?
A package is a collection of modules organized in directories. A package
contains a special file named __init__.py to indicate that the directory is a
package.
Example: Creating and Using a Package
1. Create a Package Structure:
Create the following directory structure:
my_package/
__init__.py
math_utils.py
string_utils.py
2. Add Code to Modules:
math_utils.py:
# math_utils.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
string_utils.py:
# string_utils.py
def concatenate(str1, str2):
return str1 + str2
def split_string(str, delimiter=" "):
return str.split(delimiter)
3. Use the Package in Another Script:
Create a file named main.py and use the my_package modules:
# main.py
from my_package import math_utils, string_utils
result_add = math_utils.add(5, 3)
result_subtract = math_utils.subtract(5, 3)
result_concat = string_utils.concatenate("Hello", "World")
result_split = string_utils.split_string("Hello World")
print(f"Addition: {result_add}") # Output: Addition: 8
print(f"Subtraction: {result_subtract}") # Output: Subtraction: 2
print(f"Concatenate: {result_concat}") # Output: Concatenate: HelloWorld
print(f"Split String: {result_split}") # Output: Split String: ['Hello', 'World']
Advantages of Modules and Packages
● Code Organization: Modules and packages help organize code into
smaller, manageable parts.
● Reusability: Code written in modules and packages can be reused
across different projects.
● Maintainability: Easier to maintain and update code by breaking it
into modules and packages.
● Namespace Management: Avoids conflicts by providing separate
namespaces for different modules and packages.
Popular Python Libraries and Packages
Data Analysis
1. Pandas:
○ Provides high-performance data structures and data analysis
tools.
Example:
import pandas as pd
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)
print(df)
2. NumPy:
○ Supports large, multi-dimensional arrays and matrices, along
with mathematical functions.
Example:
import numpy as np
array = np.array([1, 2, 3, 4])
print(array)
Web Development
1. Flask:
○ A lightweight web framework for building web applications.
Example:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, Flask!"
if __name__ == '__main__':
app.run(debug=True)
2. Django:
○ A high-level web framework that encourages rapid development
and clean design.
Example:
plaintext
# Command Line Instructions:
# django-admin startproject myproject
# cd myproject
# python manage.py