Modules, Packages and Virtual Environments
Turn the word-frequency script into an installable package with a src layout, a pyproject.toml and a console command, inside a virtual environment, with its development tools pinned.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: create the project and its virtual environment
- Step 2: split the script into modules
- Step 3: describe the project in pyproject.toml
- Step 4: install the package in editable mode
- Step 5: install the development tools and pin them
- Check your understanding
- Apply it: stretch tasks
- Review prompt
Lessons of Python Foundations
- Values, Control Flow, Functions and Classes Concept · 25 min
- Choosing Lists, Dicts, Sets, Tuples and Dataclasses Worked example · 20 min
- Exceptions and Defensive Input Handling Worked example · 15 min
- Modules, Packages and Virtual Environments Lab · 25 min
- Type Hints and Tests with pytest Lab · 25 min
- Check: Read, Fix and Test a Script Knowledge check · 6 questions
What you will learn
- Organize code into modules and a package, with dependencies pinned in an isolated virtual environment.
01. Goal and setup
By the end of this lab, the single wordfreq.py script from the previous lessons is a small package that you install into its own virtual environment and run as a wordfreq command. You will also pin the development tools it needs, so that anyone can recreate the same environment.
You need: Python 3.12 or later and a terminal. Check with python3 --version, or py --version on Windows. Nothing gets installed system-wide; every package in this lab goes into the project environment.
The commands are written for macOS and Linux shells, with the Windows form in a comment where it differs. The finished layout looks like this:
wordfreq/
├── .venv/ virtual environment (never committed)
├── pyproject.toml project metadata and build settings
├── requirements-dev.txt pinned development tools (step 5)
├── tickets.txt sample input
└── src/
└── wordfreq/
├── __init__.py marks the folder as a package
├── __main__.py runs the CLI for python -m wordfreq
├── cli.py argument parsing and error reporting
└── core.py tokenising, counting, ranking, reading filesWhy the extra src/ folder? It keeps the package out of the folder you run commands from, so Python cannot import it from the current directory by accident. Your code only becomes importable once it is installed, so your commands and tests use the installed package rather than whatever sits in the current folder, and most packaging mistakes show up on your machine first.
02. Step 1: create the project and its virtual environment
mkdir wordfreq && cd wordfreq
python3 -m venv .venv # Windows: py -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install --upgrade pip
python -c "import sys; print(sys.prefix != sys.base_prefix)"Truepython -m venv .venv creates a folder with its own python command, a note of which Python it was made from, and an empty site-packages folder for this project. Activating it puts .venv/bin first on your PATH, so python and pip now mean the environment copies, and your prompt usually shows (.venv). The last command proves it: inside a virtual environment, sys.prefix points at .venv while sys.base_prefix still points at the Python you started from.
Call pip as python -m pip rather than plain pip: that way pip always installs into the interpreter you just named. If you use Git, add .venv/ to .gitignore. The folder contains absolute paths, so it only works on the machine and in the location where it was created. Type deactivate to leave the environment, and activate it again in every new terminal.
03. Step 2: split the script into modules
A module is one .py file; a package is a folder of modules with an __init__.py file. Create the folders, then move the code from wordfreq.py into two modules. core.py holds the logic and load_text(); cli.py holds everything that talks to the terminal. Keeping them apart means the core can be imported and tested without parsing arguments or printing anything.
mkdir -p src/wordfreq # Windows (PowerShell): mkdir src\wordfreq"""Word counting: pure functions plus one file reader, no printing."""
import string
from collections import Counter
from dataclasses import dataclass
from pathlib import Path
STOP_WORDS = frozenset(
{"a", "an", "and", "for", "i", "in", "is", "it", "of", "on", "the", "to"}
)
@dataclass(frozen=True, slots=True)
class WordCount:
word: str
count: int
class InputError(Exception):
"""Bad input the user can fix; the CLI reports it without a traceback."""
def __init__(self, path: Path, reason: str) -> None:
super().__init__(f"{path}: {reason}")
self.path = path
self.reason = reason
def load_text(path: Path) -> str:
"""Read a UTF-8 text file; raise InputError for problems the user can fix."""
try:
with open(path, encoding="utf-8") as file:
return file.read()
except FileNotFoundError as err:
raise InputError(path, "file not found") from err
except UnicodeDecodeError as err:
raise InputError(path, "not UTF-8 text") from err
def tokenize(text: str) -> list[str]:
"""Lower-case the text, split on whitespace, strip punctuation at each end."""
words = [raw.strip(string.punctuation) for raw in text.lower().split()]
return [word for word in words if word]
def count_words(
words: list[str], stop_words: frozenset[str] = STOP_WORDS
) -> Counter[str]:
return Counter(word for word in words if word not in stop_words)
def top_words(counts: Counter[str], n: int) -> list[WordCount]:
"""Most frequent words first; ties in alphabetical order."""
if n < 1:
raise ValueError(f"n must be at least 1, got {n}")
ranked = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
return [WordCount(word, count) for word, count in ranked[:n]]"""Command-line entry point: parse arguments, call the core, report errors."""
import argparse
import sys
from pathlib import Path
from wordfreq.core import InputError, count_words, load_text, tokenize, top_words
def positive_int(value: str) -> int:
"""argparse type for --top: a whole number of at least 1."""
number = int(value) # int("ten") raises ValueError
if number < 1:
raise argparse.ArgumentTypeError(f"must be at least 1, got {number}")
return number
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
prog="wordfreq", description="Print the most frequent words in a text file."
)
parser.add_argument("path", type=Path, help="UTF-8 text file to read")
parser.add_argument("--top", type=positive_int, default=10, help="words to show")
args = parser.parse_args(argv)
try:
text = load_text(args.path)
except InputError as err:
print(f"wordfreq: error: {err}", file=sys.stderr)
return 1
for record in top_words(count_words(tokenize(text)), args.top):
print(record)
return 0
if __name__ == "__main__":
sys.exit(main())"""Count word frequencies in a text file."""import sys
from wordfreq.cli import main
sys.exit(main())cli.py imports from the package by its full name: from wordfreq.core import ... is an absolute import. Python searches the folders listed in sys.path for a top-level wordfreq package, then for the core module inside it. Within a package you may also write the relative form, from .core import .... __init__.py runs the first time anything imports the package, and __main__.py is what Python runs for python -m wordfreq.
Save the sample input as tickets.txt in the project folder, then try running the CLI file directly.
Refund not received. I asked for a refund on Monday!
The app crashed when I opened the invoice.
Invoice shows the wrong amount, please refund.python src/wordfreq/cli.py tickets.txtTraceback (most recent call last):
File ".../wordfreq/src/wordfreq/cli.py", line 7, in <module>
from wordfreq.core import InputError, count_words, load_text, tokenize, top_words
ModuleNotFoundError: No module named 'wordfreq'This failure is expected. Running a file by its path puts that file's own folder, src/wordfreq, at the front of the module search path, not src, so there is no top-level wordfreq for the import to find. The fix is not to patch paths by hand but to install the package, which takes the next two steps.
04. Step 3: describe the project in pyproject.toml
[build-system]
requires = ["setuptools>=69"]
build-backend = "setuptools.build_meta"
[project]
name = "wordfreq"
version = "0.1.0"
description = "Print the most frequent words in a text file."
requires-python = ">=3.12"
dependencies = []
[project.optional-dependencies]
dev = ["pytest>=9", "mypy>=2"]
[project.scripts]
wordfreq = "wordfreq.cli:main"python -c "import tomllib; tomllib.load(open('pyproject.toml', 'rb')); print('ok')"okpyproject.toml is the standard file for describing a Python project, and the check above uses the standard-library tomllib module to confirm it is valid TOML. Its tables do four jobs:
[build-system]names the tool that turns your source into an installable package. This lab uses setuptools, which finds packages undersrc/automatically; other build back-ends such as Hatchling work too.[project]holds the metadata.dependencieslists what the package needs at run time, as version ranges. This tool only uses the standard library, so the list is empty.[project.optional-dependencies]defines an extra calleddevfor tools you need while developing but users do not. An extra is published with the package, so anyone could installwordfreq[dev]. The Python Packaging User Guide also describes a[dependency-groups]table (PEP 735) for development tasks such as testing and linting; a group is never published with the package, and installing a group needs pip 25.1 or later (python -m pip install --group dev). This lab uses an extra becausepip install -e ".[dev]"works with every pip that Python 3.12 ships.[project.scripts]asks the installer to create awordfreqcommand that importswordfreq.cliand callsmain(). Becausemain()returns an exit code, the command passes it on to the shell.
05. Step 4: install the package in editable mode
python -m pip install -e .
wordfreq tickets.txt --top 3
python -m wordfreq tickets.txt --top 3...
Successfully installed wordfreq-0.1.0
WordCount(word='refund', count=3)
WordCount(word='invoice', count=2)
WordCount(word='amount', count=1)
WordCount(word='refund', count=3)
WordCount(word='invoice', count=2)
WordCount(word='amount', count=1)pip install -e . builds the project in the current folder and installs it into the active environment in editable mode. Instead of copying your code into site-packages, it records a pointer to src/, so edits to your modules take effect the next time you run the command. Changes to pyproject.toml itself, such as a new dependency or a new command, only apply after you install again.
Both commands run the same main(): the first through the wordfreq script that pip generated in .venv/bin, the second through __main__.py. The build also leaves a src/wordfreq.egg-info folder of metadata; add it to .gitignore next to .venv/.
06. Step 5: install the development tools and pin them
python -m pip install -e ".[dev]"
python -m pip freeze --exclude-editable > requirements-dev.txt
cat requirements-dev.txt # Windows: type requirements-dev.txtast_serialize==0.13.1
iniconfig==2.3.1
librt==0.16.0
mypy==2.4.1
mypy_extensions==1.2.0
packaging==26.3
pathspec==1.1.1
pluggy==1.7.0
Pygments==2.21.0
pytest==9.2.0
typing_extensions==4.16.0The quotes around .[dev] stop shells such as zsh from reading the square brackets as a file pattern. pip freeze lists every package in the environment with its exact version; --exclude-editable leaves out your own project, which is installed from source rather than from a version. Commit requirements-dev.txt with the code.
The two files do different jobs. pyproject.toml says what your package is compatible with, as ranges such as pytest>=9, so that it can share an environment with other packages. The requirements file records the exact set you tested with, including indirect dependencies such as pluggy, so that a teammate or a CI job gets the same versions with python -m pip install -r requirements-dev.txt.
pip freeze is the simplest way to produce the pins, but it records whatever happens to be installed, including leftovers from experiments. Tools such as pip-tools (pip-compile) and uv (uv pip compile, or uv lock for its own lock file format) work the other way round: they resolve the pins from the ranges in pyproject.toml and can record a hash for every file as well.
07. Check your understanding
08. Apply it: stretch tasks
Prove that the pins work, then extend the CLI:
- In another folder, create and activate a fresh virtual environment. Run
python -m pip install -r path/to/wordfreq/requirements-dev.txt, thenpython -m pip install --no-deps -e path/to/wordfreq, and compare the output ofpython -m pip freeze --exclude-editablewith the requirements file. They should match line for line. - Add a
--versionflag that prints the installed version. Read the version withimportlib.metadata.version("wordfreq")instead of repeating0.1.0in your code, so thatpyproject.tomlstays the single source of truth.argparsehas a ready-madeaction="version"for this. - If you use Git, commit the project with a
.gitignorethat excludes.venv/,*.egg-info/and__pycache__/.
09. Review prompt
Without looking back:
- What is the difference between a module and a package, and what do
__init__.pyand__main__.pyeach do? - What does activating a virtual environment change, and how can you check that one is active?
- What does
pip install -e .do differently from a normal install, and when must you run it again? - Why does the project keep version ranges in
pyproject.tomland exact versions in a requirements file?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.