Modules and Packages

As programs grow, you need to organize code into reusable pieces. Python uses modules and packages for this.

What You’ll Learn

  • What modules and packages are
  • How to import code with import
  • The Python standard library
  • Installing third-party packages with uv / pip
  • How to organize your own code into modules

Concept: Modules and Packages

  • A module is a single .py file containing Python code (functions, classes, variables)
  • A package is a folder of modules (with an __init__.py file)
  • The standard library is a collection of modules that come with Python (no installation needed)
  • Third-party packages are written by the community and installed separately (e.g., pandas, matplotlib)

Think of it like a golf bag: - Your bag (package) holds clubs (modules) - Each club (module) has a specific purpose - Some clubs come standard, others you buy separately - You pick the right club for the shot (import what you need)


Code: Importing Modules

The import Statement

The most basic way to use a module:

# Import the entire module
import math

# Use it with the module name as a prefix
# Calculate the distance of a drive using the Pythagorean theorem
carry_distance = 245  # yards forward
offline_distance = 30  # yards right

total_distance = math.sqrt(carry_distance**2 + offline_distance**2)
print(f"Carry: {carry_distance} yards")
print(f"Offline: {offline_distance} yards")
print(f"Actual distance from tee: {total_distance:.1f} yards")

from ... import ...

Import specific items from a module — no prefix needed:

from math import sqrt, pi

# Calculate the area of a green (assuming circular)
green_radius_yards = 15
green_area = pi * green_radius_yards**2

# Convert to square feet (1 yard = 3 feet, so 1 sq yard = 9 sq feet)
green_area_sqft = green_area * 9
print(f"Green radius: {green_radius_yards} yards")
print(f"Green area: {green_area_sqft:,.0f} sq ft")

Import with an Alias

Some packages have conventional short names:

# These aliases are standard conventions — you'll see them everywhere
import random as rng

# Simulate some golf scores using random
rng.seed(42)  # Makes results reproducible

clubs = ["Driver", "3-Wood", "7-Iron", "PW", "Putter"]
random_club = rng.choice(clubs)
print(f"Random club selection: {random_club}")

# Later in the course, you'll use these standard aliases:
# import pandas as pd
# import numpy as np
# import matplotlib.pyplot as plt

Useful Standard Library Modules

These come with Python — no installation needed:

# random — generate random data
import random
random.seed(42)

# Simulate a 4-player group's scores on a par 4
for i in range(4):
    score = random.randint(3, 7)  # Random score between 3 and 7
    print(f"Player {i + 1}: {score}")
# datetime — work with dates and times
from datetime import date, timedelta

round_date = date(2024, 3, 15)
next_round = round_date + timedelta(days=7)

print(f"Round played: {round_date}")
print(f"Next round: {next_round}")
print(f"Day of week: {round_date.strftime('%A')}")
# statistics — basic statistical functions
import statistics

recent_scores = [78, 82, 75, 80, 77, 83, 79, 76, 81, 78]

print(f"Scores: {recent_scores}")
print(f"Average: {statistics.mean(recent_scores):.1f}")
print(f"Median: {statistics.median(recent_scores):.1f}")
print(f"Std Dev: {statistics.stdev(recent_scores):.1f}")
print(f"Low round: {min(recent_scores)}")
print(f"High round: {max(recent_scores)}")
# csv and json — reading data files (we'll dive deep in Topic 03)
import csv
import json

# Quick preview — these are the formats our golf data uses
print("CSV is for tabular data (spreadsheet-like)")
print("JSON is for structured/nested data")
print("\nWe'll use both extensively starting in Topic 03.")

Installing Third-Party Packages

Packages not in the standard library need to be installed. Use uv (or pip):

# Install a package
uv pip install pandas

# Install multiple packages
uv pip install pandas matplotlib seaborn

# Install from the project's pyproject.toml (all course dependencies)
uv pip install -e ".[dev]"

If you set up the course environment in notebook 01, all the packages are already installed.

Creating Your Own Module

Any .py file is a module. Let’s say you create golf_utils.py:

# golf_utils.py

def format_score(score: int, par: int) -> str:
    """Format a score relative to par."""
    diff = score - par
    if diff > 0:
        return f"+{diff}"
    elif diff < 0:
        return str(diff)
    return "E"


def scoring_name(score: int, par: int) -> str:
    """Return the golf name for a score (birdie, bogey, etc.)."""
    diff = score - par
    names = {
        -3: "Double Eagle",
        -2: "Eagle",
        -1: "Birdie",
         0: "Par",
         1: "Bogey",
         2: "Double Bogey",
         3: "Triple Bogey",
    }
    return names.get(diff, f"{diff:+d}")

Then use it anywhere:

from golf_utils import format_score, scoring_name

print(format_score(78, 72))     # +6
print(scoring_name(3, 4))       # Birdie

Tip: As you build up useful functions throughout this course, save them in a golf_utils.py module you can reuse.


AI: Using AI to Discover and Learn Packages

One of the best uses of AI is discovering what’s available. The Python ecosystem has thousands of packages, and AI tools know about most of them.

Exercise 1: Find the Right Package

Try this prompt with Claude or ChatGPT:

“I’m building a golf data analysis project in Python. What packages should I use for: reading CSV files, data analysis, and creating charts? Just give me the package names, a one-line description, and the conventional import alias for each.”

Exercise 2: Understand Unfamiliar Code

When you encounter an import you don’t recognize, ask AI:

“What does from pathlib import Path do? When would I use it instead of os.path? Give me a simple example.”

Exercise 3: Generate a Module

Try asking AI to create a utility module:

“Create a Python module called golf_scoring.py with functions for: calculating handicap differential, converting between gross and net score, and determining scoring type name (eagle, birdie, par, etc.) for a hole. Include type hints and docstrings.”

Evaluate the result: - Does the handicap calculation look correct? (Look up the USGA formula to check) - Are the type hints accurate? - Would you organize the functions differently?

# Paste and test AI-generated code here

Summary

  • Modules are .py files with reusable code
  • Packages are folders of modules
  • import math, from math import sqrt, import pandas as pd — three ways to import
  • The standard library (random, datetime, statistics, csv, json) comes free with Python
  • Third-party packages (pandas, matplotlib) are installed with uv pip install
  • AI is great for discovering packages and understanding unfamiliar imports

Next topic: Python Basics — decision structures, loops, and functions, all with golf examples.

Get the Complete Course Bundle

All notebooks, the full golf dataset, and new tutorials — straight to your inbox.