Back to blog
← View series: python tutorials

~/blog

Modules & Packages

Apr 1, 2026β€’5 min readβ€’By Mohammed Vasim
PythonProgrammingTutorialBeginner

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:

python
# 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:

python
# 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

python
# 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.0

When to Use What

Import StyleUse When
import moduleUsing multiple items from module
from module import specificUsing one or few items
import module as aliasModule 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

python
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.0

random Module

python
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

python
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, 2024

json Module

python
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

python
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

bash
# Install a package
pip install requests

# Install specific version
pip install requests==2.28.0

# Upgrade
pip install --upgrade requests

# Uninstall
pip uninstall requests
PackagePurpose
requestsHTTP requests
numpyNumerical computing
pandasData analysis
matplotlibData visualization
flaskWeb framework
djangoFull web framework

Using Installed Packages

python
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:

python
# __init__.py
from .module1 import function1
from .module2 import function2

__version__ = "1.0.0"
__all__ = ["function1", "function2"]

Using the Package

python
# Import from package
import my_package
my_package.function1()

# Or import specific
from my_package import function1

# From subpackage
from my_package.subpackage import module3

Practical Example: Calculator Package

Create the Package

calculator/ β”œβ”€β”€ __init__.py β”œβ”€β”€ operations.py └── helpers.py
python
# 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
python
# 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
python
# __init__.py
from .operations import add, subtract, multiply, divide
from .helpers import validate_numbers

__all__ = ["add", "subtract", "multiply", "divide", "validate_numbers"]

Using the Package

python
# 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:

  1. A module text.py with functions: reverse_string(), count_vowels(), is_palindrome()
  2. A module format.py with functions: to_title_case(), remove_whitespace()
  3. An __init__.py that exports all functions
  4. A test script that uses the package
Click to see solution
python
# 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')}")  # helloworld

Output:

=== 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.

Introduction to OOP β†’

Comments (0)

No comments yet. Be the first to comment!

Leave a comment