Skip to content

7. Modules & packages

Beginner · 7 min read

A module is any .py file; a package is a folder of modules. Imports let you split code across files and use other people's libraries.

7.1 Importing

import math                          # import a whole module
from pathlib import Path             # import one name from a module
from datetime import datetime as dt  # rename on import
import json, os                      # several at once (fine for quick scripts)

print(math.sqrt(16))                 # → 4.0
print(Path("notes/rag.md").suffix)   # → .md
print(dt(2026, 1, 1).year)           # → 2026

7.2 The standard library

Python ships with "batteries included". The modules you'll use most:

Module Use it for
pathlib file paths that work on Windows and macOS
json reading/writing JSON (API payloads, configs)
os environment variables, the operating system
datetime dates and times
re regular expressions (pattern matching in text)
collections Counter, defaultdict, deque
logging proper logs instead of print
from collections import Counter

words = "rag agents rag llm rag".split()
print(Counter(words).most_common(1))   # → [('rag', 3)]

7.3 Your own modules

text_utils.py
"""Small helpers for cleaning text."""

def clean(text):
    """Collapse whitespace and trim the ends."""
    return " ".join(text.split())
main.py
from text_utils import clean          # same folder → import by file name

print(clean("  hello    world "))     # → hello world

A folder becomes a package when you import from it: from rag.retrieval import search (an empty __init__.py inside the folder makes it explicit).

7.4 if __name__ == "__main__":

text_utils.py
def clean(text):
    return " ".join(text.split())

if __name__ == "__main__":            # True only when you run this file directly…
    print(clean("  quick   test "))   # …not when another file imports it

7.5 Installing packages with pip

pip install openai                    # install the latest version
pip install "openai>=1.40,<2"         # install within a version range
pip list                              # what's installed
pip freeze > requirements.txt         # save exact versions for your project

Always install inside a virtual environment.

A faster alternative: uv

uv creates the environment, installs packages and locks versions in one tool — see Manage a GenAI project with uv.

7.6 Secrets in environment variables

import os

# Read the key from the environment; never write keys in your code.
api_key = os.getenv("OPENAI_API_KEY", "")   # "" if it isn't set
print("key set:", bool(api_key))

With the python-dotenv package you can keep keys in a .env file (added to .gitignore) and call load_dotenv() at start-up.

Why it matters for GenAI

Every LLM project is "glue" between packages — an SDK, a vector store, a web framework. Knowing how imports, pip and environment variables work saves hours of setup errors.

Practice

  • Use Counter to find the 2 most common words in a paragraph of your choice.
  • Move a helper function into its own module and import it from main.py.