Modules and Packages – Organizing Code for Reuse

Section Overview

As your Python programs grow, keeping everything in one file becomes impractical. This section teaches you how to break your code into modules and packages, making it easier to organize, reuse, and maintain.

By the end of this section, you will be able to:

  • Create and use custom Python modules
  • Understand the import system
  • Structure your code into reusable packages
  • Use standard library modules to avoid reinventing the wheel

Lesson 1: What Is a Module?

A module is simply a .py file that contains Python code — functions, variables, or classes — that can be reused in other programs.

Example:

Create a file called math_utils.py:

def square(x):
    return x * x

def cube(x):
    return x * x * x

Then in another file:

import math_utils

print(math_utils.square(3))  # Outputs: 9 

You can also use:

from math_utils import cube
print(cube(2))  # Outputs: 8 

Lesson 2: Aliasing and Selective Import

You can rename modules when importing:

import math_utils as mu
print(mu.square(4))

To import just what you need:

from math_utils import square

Lesson 3: What Is a Package?

A package is a folder containing a special file called __init__.py and other module files. This structure allows for multi-file libraries.

Example structure:

my_package/
│
├── __init__.py
├── utils.py
└── string_helpers.py

Then in a script:

from my_package import utils
from my_package.string_helpers import capitalize_first

utils.do_something()

Lesson 4: Using the Standard Library

Python comes with many built-in modules that you can start using right away:

import math
print(math.sqrt(16))  # 4.0

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

Other commonly used modules:

  • os – interacting with the file system
  • random – generating random numbers
  • sys – accessing command-line arguments

Quiz: Check Your Understanding

1. What is a module in Python?
Answer: A .py file containing code you can reuse.

2. How do you import only one function from a module?
Answer: from module import function_name

3. What file must a folder contain to be considered a package?
Answer: __init__.py

4. Name a built-in Python module used for random number generation.
Answer: random


Practice Exercise: Create a Personal Utilities Module

  1. Create a file my_utils.py
  2. Add two functions: greet(name) and days_until_birthday(month, day)
  3. Use this module in another file to test both functions
# my_utils.py from datetime import date

def greet(name):
    return f"Hello, {name}!"

def days_until_birthday(month, day):
    today = date.today()
    next_birthday = date(today.year, month, day)
    if next_birthday < today:
        next_birthday = date(today.year + 1, month, day)
    return (next_birthday - today).days