Modules#

This section teaches how modules work in Python and how quickly you can build your own reusable modules for projects.

Learning Goals

  • Explain what a Python module is

  • Create a custom module file

  • Import and use module functions in another file/notebook

  • Organize module code in a project-friendly way

What Is a Module?#

A module is a Python file (.py) that contains reusable code (functions, classes, variables).

Why this matters for projects:

  • You avoid copy-pasting logic

  • You separate concerns (I/O, processing, utilities)

  • You can test and reuse functionality across files

# Built-in module example
import math

print(math.sqrt(81))
print(math.pi)
9.0
3.141592653589793

Create and Import Your Own Module#

A custom module is just a .py file. The example below writes a module file, imports it, and reuses its functions.

from pathlib import Path
import sys

module_dir = Path('.')
module_dir.mkdir(parents=True, exist_ok=True)
module_path = module_dir / 'my_math_tools.py'

module_path.write_text(
    "def square(x):\n"
    "    return x * x\n\n"
    "def cube(x):\n"
    "    return x * x * x\n",
    encoding='utf-8'
)

if str(module_dir.resolve()) not in sys.path:
    sys.path.insert(0, str(module_dir.resolve()))

import my_math_tools

print(my_math_tools.square(6))
print(my_math_tools.cube(3))
36
27
### Exercise: Build a Tax Module
# Create a file `pricing_tools.py` with a function:
# `add_tax(price, rate=0.07)` that returns price with tax.
# Then import it and calculate the taxed value of 49.99.
### Your code starts here.


### Your code ends here.

Hide code cell source

### Solution
from pathlib import Path
import sys

module_dir = Path('.')
module_dir.mkdir(parents=True, exist_ok=True)
module_path = module_dir / 'pricing_tools.py'
module_path.write_text(
    "def add_tax(price, rate=0.07):\n"
    "    return price * (1 + rate)\n",
    encoding='utf-8'
)

if str(module_dir.resolve()) not in sys.path:
    sys.path.insert(0, str(module_dir.resolve()))

import pricing_tools
print(round(pricing_tools.add_tax(49.99), 2))
53.49

Module Design for Projects#

Simple project pattern:

  • one file for entry point (main.py)

  • one or more module files for reusable logic (utils.py, data_ops.py, etc.)

Keep module functions:

  • small

  • single-purpose

  • well-named

  • easy to test

# Example project-style split (conceptual)
# main.py
# from my_math_tools import square
# print(square(10))

# my_math_tools.py
# def square(x):
#     return x * x

Summary#

If students can build one custom module, they can scale to small projects:

  • define reusable functions once

  • import where needed

  • keep project code organized