Python Modules and Packages: The Complete Beginner's Guide

This chapter shows how to scale beyond one file using modules and packages, master import patterns, use the standard library, install third-party packages with pip, and isolate dependencies with virtual environments.

Chapter 13 of 20 · Intermediate · 40 min · Python Programming Course

Every Python program you have written so far can live in one file. Real projects cannot. Modules and packages let you split code into reusable, maintainable pieces.

What You Will Learn in This Chapter

By the end of this tutorial you will be able to:

  • Import modules with import, from ... import, and aliases
  • Use core standard-library modules effectively
  • Create and import your own modules
  • Understand module lookup using sys.path
  • Build packages with __init__.py
  • Install third-party packages with pip
  • Use virtual environments for dependency isolation
  • Avoid common import pitfalls

Estimated time: 40 minutes reading + 20 minutes practice

The Three Import Styles

1) import module

import math
print(math.sqrt(16))

2) from module import name

from math import sqrt, pi
print(sqrt(25), pi)

3) import module as alias

import datetime as dt
print(dt.date.today())

Avoid wildcard imports:

from math import *   # avoid

Standard Library Essentials

math

import math
print(math.pi, math.sqrt(144), math.factorial(6))

random

import random
random.seed(42)
print(random.randint(1, 100))

datetime

from datetime import datetime, timedelta
now = datetime.now()
print(now + timedelta(days=1))

os

import os
print(os.getcwd())
print(os.path.join("data", "output.csv"))

sys

import sys
print(sys.version)
print(sys.path)

json

import json
data = {"name": "Alice", "age": 25}
raw = json.dumps(data, indent=2)
print(json.loads(raw)["name"])

collections

from collections import Counter, defaultdict, deque
print(Counter(["python", "python", "java"]))

Creating Your Own Module

Any .py file is a module.

mathutils.py:

PI = 3.14159265358979

def circle_area(radius):
    return PI * radius ** 2

main.py:

import mathutils
print(mathutils.circle_area(5))

How Python Finds Modules

Python searches import locations in order including current directory, environment paths, stdlib, and site-packages.

import sys
print(sys.path)

__name__ Guard

def circle_area(radius):
    return 3.14159 * radius ** 2

if __name__ == "__main__":
    print(circle_area(5))

Creating Packages

A package is a directory with modules and typically __init__.py.

# schoolabe/__init__.py
from .math_tools import add
__version__ = "1.0.0"

Installing Third-Party Packages with pip

pip install requests
pip freeze > requirements.txt
pip install -r requirements.txt

Virtual Environments

python -m venv venv
source venv/bin/activate
pip install requests
deactivate

Use a virtual environment per project to prevent version conflicts.

A Complete Working Program

Below is a compact report utility that combines standard library modules:

import math
import json
import random
from datetime import datetime, timedelta
from collections import Counter, defaultdict

random.seed(42)

def generate_sales_data(n=20):
    products = ["Python", "Kafka", "DSA", "JS"]
    records = []
    start = datetime(2026, 1, 1)
    for i in range(n):
        records.append({
            "id": f"TXN{i+1:04d}",
            "date": (start + timedelta(days=random.randint(0, 60))).strftime("%Y-%m-%d"),
            "product": random.choice(products),
            "amount": round(random.uniform(30, 300), 2),
        })
    return records

def report(records):
    amounts = [r["amount"] for r in records]
    totals = defaultdict(float)
    for r in records:
        totals[r["product"]] += r["amount"]
    return {
        "generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "count": len(records),
        "total": round(sum(amounts), 2),
        "mean": round(sum(amounts) / len(amounts), 2),
        "std_dev": round(math.sqrt(sum((x - (sum(amounts)/len(amounts)))**2 for x in amounts)/len(amounts)), 2),
        "top_products": Counter(r["product"] for r in records).most_common(3),
        "revenue_by_product": dict(sorted(totals.items(), key=lambda x: x[1], reverse=True)),
    }

5 Import Mistakes Every Beginner Makes

  1. Naming your file like stdlib modules (random.py, json.py)
  2. Circular imports between modules
  3. Wildcard imports (from x import *)
  4. Missing or misusing package __init__.py
  5. Installing globally instead of inside a virtual environment

Practice Exercises

  • Standard library mini report with math, random, datetime
  • Build a custom text_utils.py and import it from main.py
  • JSON write/read workflow for student records
  • os-based Python file listing utility
  • collections usage with Counter, defaultdict, deque

-> See all Python practice exercises with solutions

What Comes Next - Day 14: File Handling

Day 14 moves from code organisation to persistent data:

  • opening/closing files safely
  • reading/writing/appending content
  • CSV handling
  • path operations with pathlib
  • safe file error handling

-> Continue to Day 14: File Handling

Frequently Asked Questions

What is a module in Python?

A module is any .py file containing Python code.

What is the difference between a module and a package?

A module is one file. A package is a directory of modules.

What is the difference between import styles?

import x keeps namespace explicit, from x import y imports directly, aliases shorten long names.

What does if __name__ == "__main__" mean?

It runs code only when the file is executed directly, not when imported.

What is pip in Python?

pip installs Python packages from PyPI and manages dependencies.

What is a virtual environment in Python?

An isolated environment for project-specific dependencies.

What is __init__.py in a package?

A package initializer that marks package boundaries and controls exports.

What is sys.path in Python?

A list of paths Python searches during import resolution.

Chapter navigation

Frequently asked questions: Modules and packages

What is a module in Python?

A module is any .py file containing Python code such as functions, classes, and variables.

What is the difference between a module and a package?

A module is a single file. A package is a directory containing related modules.

What is the difference between import math and from math import sqrt?

import math keeps namespaced access (math.sqrt). from math import sqrt imports a specific name directly (sqrt).

What does if __name__ == "__main__": mean in Python?

It runs code only when a file is executed directly, not when imported as a module.

What is pip in Python?

pip is Python’s package installer used to install, upgrade, and manage third-party packages.

What is a virtual environment in Python?

A virtual environment isolates project dependencies so package versions do not conflict across projects.

What is __init__.py in a Python package?

__init__.py marks package boundaries and can control which names are exported at package level.

What is sys.path in Python?

sys.path lists directories Python searches when resolving imports.