Chapter 3 · Writing Real Programs
Modules, Packages and pip
- Page 9 of 20
- 4 min read
Nobody writes an AI application from scratch. You stand on code other people have written and shared: Python's own standard library, which comes with Python, and hundreds of thousands of packages on PyPI, installed with pip. This page shows how to use both — and how to split your own code into files.
Importing
A module is simply a Python file whose functions and variables you can use from another file. import brings one in. There are three common forms:
| Form | Then you write | When |
|---|---|---|
import math | math.sqrt(2) | Default: clear where each name comes from |
from math import sqrt | sqrt(2) | You use one or two names a lot |
import numpy as np | np.array(...) | A long name with a well-known short alias |
Avoid from module import *: it dumps every name into your file and hides where things came from.
The standard library: batteries included
Python ships with modules for maths, dates, randomness, files, JSON, the internet and much more. A few you will use constantly:
import math
from random import choice, seed
from datetime import date, timedelta
from collections import Counter
print(math.sqrt(144), math.ceil(4.2), math.pi)
seed(42) # same "random" result every run
print(choice(["red", "green", "blue"]))
exam_day = date(2026, 12, 1)
print(exam_day + timedelta(days=30))
words = "to be or not to be".split()
print(Counter(words).most_common(2))12.0 5 3.141592653589793
blue
2026-12-31
[('to', 2), ('be', 2)]Counter counts things for you — word frequencies in one line. seed(42) makes the "random" choice the same every time, which is what you want when an experiment must be repeatable. Machine learning code sets seeds for exactly this reason.
import statistics as stats
latencies_ms = [220, 180, 950, 210, 205]
print(stats.mean(latencies_ms))
print(stats.median(latencies_ms)) # not pulled up by one slow call353
210One slow API call (950 ms) drags the mean up; the median shows the typical case. Knowing which summary to report is part of working with data.
Your own modules
Once a file grows past a few hundred lines, split it. Put related functions in their own file and import them. Here is a module, text_tools.py:
# text_tools.py
"""Small helpers for working with text."""
def clean(text):
"""Collapse runs of whitespace into single spaces."""
return " ".join(text.split())
def word_count(text):
return len(text.split())
if __name__ == "__main__":
# Runs only when this file is run directly, not when imported.
print(clean(" quick self-test "))and a program next to it that uses it:
# main.py
from text_tools import clean, word_count
note = " Python is fun "
print(clean(note))
print(word_count(note))Python is fun
3Notice the self-test did not print: the block under if __name__ == "__main__": runs only when you run python text_tools.py directly. Use it for a quick demo or test of a module without it running every time someone imports it.
A folder of modules is a package. When you write from openai import OpenAI, you are importing from the openai package you installed with pip.
pip and requirements.txt
python -m pip install requests # install the newest version
python -m pip install "pandas>=3,<4" # a version range
python -m pip list # what is installed
python -m pip freeze > requirements.txt # save exact versions
python -m pip install -r requirements.txt # recreate on another computerrequirements.txt is a plain text list of the packages (and versions) your project needs. Commit it with your code, and anyone — including a server — can install exactly what your program expects. Always run these commands inside your project's virtual environment (page 2).
Before installing a package, check it is the real one: look at its PyPI page, its download count and its source repository. Attackers publish look-alike names (for example
reqeusts) hoping for typos.
Try it yourself
- Use
Counterto find the three most common words in a paragraph of your choice. - Use
datetime.date.today()to print how many days are left until your next exam. - Move the
count_wordsfunction from page 7 into its own module and import it.