β View series: python tutorials
~/blog
Modules & Packages
Introduction
In this tutorial, you'll learn how to organize your Python code into modules and packages. This allows you to reuse code across files and projects, and use the vast ecosystem of Python libraries.
What You'll Learn
- What are modules
- Creating and importing modules
- The import statement variations
- Standard library modules
- Installing external packages with pip
- Creating packages
What are Modules?
A module is simply a Python file (.py file) containing code you can reuse. Modules help organize code into manageable, reusable pieces.
Creating a Module
Create a file named greetings.py:
# greetings.py
def say_hello(name):
return f"Hello, {name}!"
def say_goodbye(name):
return f"Goodbye, {name}!"
def say_welcome(name):
return f"Welcome, {name}!"
# You can also define variables
VERSION = "1.0.0"Using a Module
In another file:
# main.py
import greetings
# Call functions from the module
print(greetings.say_hello("Alice"))
print(greetings.say_goodbye("Bob"))
# Access variables
print(greetings.VERSION)Import Statements
Different Import Styles
# Import entire module
import math
print(math.sqrt(16)) # 4.0
# Import specific items
from math import sqrt, pi
print(sqrt(16)) # 4.0
print(pi) # 3.14159...
# Import with alias (aliasing)
import math as m
print(m.sqrt(16)) # 4.0
# Import everything (not recommended)
from math import *
print(sqrt(16)) # 4.0When to Use What
| Import Style | Use When |
|---|---|
import module | Using multiple items from module |
from module import specific | Using one or few items |
import module as alias | Module name is long or conflicts |
from module import * | Rarely - can cause name conflicts |
Standard Library Modules
Python comes with a rich standard library. Here are commonly used ones:
math Module
import math
print(math.pi) # 3.14159...
print(math.e) # 2.71828...
print(math.sqrt(16)) # 4.0
print(math.floor(3.7)) # 3
print(math.ceil(3.2)) # 4
print(math.sin(math.pi / 2)) # 1.0random Module
import random
print(random.randint(1, 10)) # Random integer 1-10
print(random.random()) # Random float 0-1
print(random.choice([1, 2, 3])) # Random choice from list
print(random.shuffle([1, 2, 3])) # Shuffle list in place
# Generate random password
import string
chars = string.ascii_letters + string.digits
password = ''.join(random.choice(chars) for _ in range(8))
print(password)datetime Module
import datetime
# Current date and time
now = datetime.datetime.now()
print(now) # 2024-01-15 10:30:45.123456
# Specific date
date = datetime.date(2024, 1, 15)
print(date) # 2024-01-15
# Date arithmetic
from datetime import timedelta
tomorrow = now + timedelta(days=1)
print(tomorrow)
# Format dates
print(now.strftime("%Y-%m-%d")) # 2024-01-15
print(now.strftime("%B %d, %Y")) # January 15, 2024json Module
import json
# Convert Python to JSON
data = {"name": "Alice", "age": 25}
json_str = json.dumps(data)
print(json_str) # {"name": "Alice", "age": 25}
# Convert JSON to Python
parsed = json.loads(json_str)
print(parsed) # {'name': 'Alice', 'age': 25}
# Write to file
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
# Read from file
with open("data.json", "r") as f:
loaded = json.load(f)os Module
import os
# File operations
print(os.getcwd()) # Current directory
os.mkdir("new_folder") # Create directory
os.rename("old", "new") # Rename
os.remove("file.txt") # Delete file
os.path.exists("file.txt") # Check if exists
# List files
print(os.listdir("."))Installing External Packages
Python has a vast ecosystem of packages. Install them using pip.
Using pip
# Install a package
pip install requests
# Install specific version
pip install requests==2.28.0
# Upgrade
pip install --upgrade requests
# Uninstall
pip uninstall requestsPopular Packages
| Package | Purpose |
|---|---|
requests | HTTP requests |
numpy | Numerical computing |
pandas | Data analysis |
matplotlib | Data visualization |
flask | Web framework |
django | Full web framework |
Using Installed Packages
import requests
response = requests.get("https://api.github.com")
print(response.status_code)
print(response.json())Creating Packages
A package is a directory containing multiple modules and a special __init__.py file.
Package Structure
my_package/
βββ __init__.py
βββ module1.py
βββ module2.py
βββ subpackage/
βββ __init__.py
βββ module3.py
init.py
This file makes a directory a package. It can be empty or contain initialization code:
# __init__.py
from .module1 import function1
from .module2 import function2
__version__ = "1.0.0"
__all__ = ["function1", "function2"]Using the Package
# Import from package
import my_package
my_package.function1()
# Or import specific
from my_package import function1
# From subpackage
from my_package.subpackage import module3Practical Example: Calculator Package
Create the Package
calculator/
βββ __init__.py
βββ operations.py
βββ helpers.py
# operations.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b# helpers.py
def validate_numbers(*numbers):
for num in numbers:
if not isinstance(num, (int, float)):
raise TypeError(f"{num} is not a number")
return True# __init__.py
from .operations import add, subtract, multiply, divide
from .helpers import validate_numbers
__all__ = ["add", "subtract", "multiply", "divide", "validate_numbers"]Using the Package
# main.py
from calculator import add, divide, validate_numbers
try:
validate_numbers(10, 5)
result = divide(10, 5)
print(f"Result: {result}")
except (TypeError, ValueError) as e:
print(f"Error: {e}")Summary
In this tutorial, you learned:
- β What modules are and how to create them
- β Different import statement styles
- β Common standard library modules
- β Installing external packages with pip
- β Creating your own packages
π§βπ» Practice Exercise
Create a package called string_utils with:
- A module
text.pywith functions:reverse_string(),count_vowels(),is_palindrome() - A module
format.pywith functions:to_title_case(),remove_whitespace() - An
__init__.pythat exports all functions - A test script that uses the package
Click to see solution
# Create folder structure:
# string_utils/
# βββ __init__.py
# βββ text.py
# βββ format.py
# text.py
def reverse_string(text):
return text[::-1]
def count_vowels(text):
vowels = "aeiouAEIOU"
return sum(1 for char in text if char in vowels)
def is_palindrome(text):
cleaned = text.lower().replace(" ", "")
return cleaned == cleaned[::-1]
# format.py
def to_title_case(text):
return text.title()
def remove_whitespace(text):
return "".join(text.split())
# __init__.py
from .text import reverse_string, count_vowels, is_palindrome
from .format import to_title_case, remove_whitespace
__all__ = [
"reverse_string", "count_vowels", "is_palindrome",
"to_title_case", "remove_whitespace"
]
# test_string_utils.py
from string_utils import (
reverse_string, count_vowels, is_palindrome,
to_title_case, remove_whitespace
)
# Test text functions
print("=== Text Functions ===")
print(f"Reverse: {reverse_string('hello')}") # olleh
print(f"Vowels in 'hello': {count_vowels('hello')}") # 2
print(f"Is 'racecar' palindrome: {is_palindrome('racecar')}") # True
print(f"Is 'hello' palindrome: {is_palindrome('hello')}") # False
# Test format functions
print("\n=== Format Functions ===")
print(f"Title case: {to_title_case('hello world')}") # Hello World
print(f"Remove whitespace: {remove_whitespace('hello world')}") # helloworldOutput:
=== Text Functions ===
Reverse: olleh
Vowels in 'hello': 2
Is 'racecar' palindrome: True
Is 'hello' palindrome: False
=== Format Functions ===
Title case: Hello World
Remove whitespace: helloworld
What's Next
In the next tutorial, we'll learn about Object-Oriented Programming (OOP) - a paradigm for structuring code using classes and objects.