These exercises practice what the Module 18 reading explained. They aren’t graded.
Work in m18/rainkit, the project the reading built, with rainkit installed in your course
environment, and run each tool as the reading does: python -m ruff check,
python -m ruff format --check, python -m mypy src, and python -m pytest, using your
environment’s Python. Write your answer or your prediction first, then run the code to check it.
The answers are in the collapsed blocks; open one only after you have an answer of your own.
Worked example: releasing a new feature¶
rainkit 1.0.0 is out, and a user asks for the totals as JSON, so another program can read them. Here is the whole path from the request to rainkit 1.1.0.
Write the test first (Module 13). main takes its arguments as a list and returns the exit
status, so a test can call it like a function. pytest’s built-in fixture capsys captures what
the code prints: capsys.readouterr() returns an object whose out attribute holds everything
printed so far, and whose err holds what went to sys.stderr. Save this as
tests/test_cli.py:
import json
from rainkit.cli import main
def write_readings(folder):
path = folder / "rain.csv"
path.write_text("station,day,rain_mm\nHarbor,2026-11-02,1.2\n", encoding="utf-8")
return path
def test_json_prints_the_totals(tmp_path, capsys):
path = write_readings(tmp_path)
assert main(["--json", str(path)]) == 0
assert json.loads(capsys.readouterr().out) == {"Harbor": 1.2}The test fails, as it should, because argparse doesn’t know the option yet. pytest’s report
ends with:
----------------------------- Captured stderr call -----------------------------
usage: rainkit [-h] [--version] csv_file
rainkit: error: unrecognized arguments: --json
=========================== short test summary info ============================
FAILED tests/test_cli.py::test_json_prints_the_totals - SystemExit: 2
========================= 1 failed, 2 passed in 0.08s ==========================Write the code. In cli.py, add import json with the other imports from the standard
library, add the option, and print the totals as JSON when it is given. This is main now, with
its docstring brought up to date too:
def main(argv: list[str] | None = None) -> int:
"""Print each station's total rainfall and the wettest day; return the exit status."""
parser = argparse.ArgumentParser(prog="rainkit", description="Add up rain gauge readings.")
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
parser.add_argument("--json", action="store_true", help="print the totals as JSON")
parser.add_argument("csv_file", type=Path, help="a CSV file of station, day, and rain_mm")
args = parser.parse_args(argv)
try:
readings = read_readings(args.csv_file)
except (OSError, ValueError, KeyError) as error:
print(f"rainkit: can't read {args.csv_file}: {error}", file=sys.stderr)
return 1
totals = total_by_station(readings)
if args.json:
print(json.dumps(totals))
return 0
for station, total in totals.items():
print(f"{station:<10} {total:6.1f} mm")
best = wettest(readings)
if best is not None:
print(f"Wettest: {best.station} on {best.day}")
return 0action="store_true" makes --json a flag: args.json is True when the option is given, and
False otherwise. The new code changes nothing when the option is left out, so everything that
worked in 1.0.0 still works the same.
Run every check, as the workflow will:
All checks passed!
8 files already formatted
Success: no issues found in 5 source files
============================== 3 passed in 0.06s ===============================Those are the last lines of ruff check, ruff format --check, mypy src, and pytest. (Ruff
counts pyproject.toml among its files.) The
editable install already runs the new code, so try it: rainkit --json rain.csv prints
{"Harbor": 8.6, "Hilltop": 13.3}and rainkit --help lists the option, with its help text:
usage: rainkit [-h] [--version] [--json] csv_fileChoose the version. The release adds an option and breaks nothing, so MINOR goes up and PATCH
goes back to zero: 1.1.0. Set version = "1.1.0" in pyproject.toml, and install again, so
rainkit --version agrees.
Update the changelog. The new entry goes under the new version, with today’s date:
## [Unreleased]
## [1.1.0] - 2026-12-05
### Added
- The `--json` option, which prints each station's total as JSON instead of a table.Commit, tag, and push, as in the reading, after the workflow passes on GitHub:
git add tests/test_cli.py src/rainkit/cli.py pyproject.toml CHANGELOG.md
git commit -m "Add a --json option, and release 1.1.0"
git push
git tag -a v1.1.0 -m "rainkit 1.1.0"
git push origin v1.1.0Each step answered one question: what should it do (the test), does it do that (the checks), what does the change mean for users (the version and the changelog), and which code is the release (the tag).
Exercises¶
Exercise 18.1 (LO-18.1, ★, about 10 minutes)¶
Each of these changes to rainkit’s pyproject.toml makes python -m pip install -e . fail. For
each one, say what is wrong and how to fix it. Then make each change in your copy, run the
install to read pip’s message, and change it back.
rainkit = "rainkit.cli.main"under[project.scripts].name = "rain-tools"under[project], with the package still insrc/rainkit.version = 0.1under[project].
Hint
Compare each line with the reading’s pyproject.toml, character by character. pip’s message is long; read the last lines before [end of output].
Answer
The command needs a module and a function, with a colon between them:
"rainkit.cli:main". With a dot, pip reads the whole string as a module, with no function to call, and stops withInvalid script entry point: ... A callable suffix is required.Hatchling looks for a package with the project’s name, and finds none, so it stops with
Unable to determine which files to ship inside the wheel, and says why:there is no directory that matches the name of your project (rain_tools). Hatchling changes the hyphen to an underscore, because a hyphen can’t be part of an import name. Keep the project’s name and the package’s folder the same. (Hatchling has a setting to name the folder instead, which its message describes, but one name for both is simpler for everyone.)Without quotation marks, TOML reads
0.1as a number, and Hatchling stops withTypeError: Field 'project.version' must be a string. Writeversion = "0.1.0": a version is text, and0.1.0, with two dots, isn’t a number at all, so TOML wouldn’t even read it.
Exercise 18.2 (LO-18.1, ★★, about 15 minutes)¶
Add two tests to tests/test_cli.py from the worked example:
test_missing_file:mainwith the name of a file that doesn’t exist returns 1, prints nothing tosys.stdout, and prints a message tosys.stderrthat starts withrainkit: can't read.test_version:main(["--version"])printsrainkitand the installed version, and stops with the exit status 0.
Hint 1
Build the missing file’s path from tmp_path, so it can’t exist. capsys.readouterr() returns both streams at once, as out and err.
Hint 2
argparse handles --version itself: it prints the version and calls sys.exit(0), which raises SystemExit (Module 17’s practice). Catch it with pytest.raises(SystemExit) as caught, and check caught.value.code. Read the version the way __init__.py does, so the test doesn’t need changing at every release.
Answer
from importlib.metadata import version
import pytest
def test_missing_file(tmp_path, capsys):
assert main([str(tmp_path / "nowhere.csv")]) == 1
captured = capsys.readouterr()
assert captured.out == ""
assert captured.err.startswith("rainkit: can't read")
def test_version(capsys):
with pytest.raises(SystemExit) as caught:
main(["--version"])
assert caught.value.code == 0
assert capsys.readouterr().out == f"rainkit {version('rainkit')}\n"Put the new imports at the top of the file, with the others, in the groups Ruff’s I rules expect: import json and from importlib.metadata import version from the standard library, a blank line, import pytest from the installed packages, another blank line, and from rainkit.cli import main. If they are in the wrong order there, python -m ruff check --fix sorts them. Imports left further down the file are reported as E402 Module level import not at top of file, which Ruff can’t fix for you. --version goes to sys.stdout, so it is in out. Comparing it with version('rainkit'), rather than with "rainkit 1.1.0", keeps the test true after the next release.
Exercise 18.3 (LO-18.2, ★★, about 15 minutes)¶
A colleague’s new module, src/rainkit/summary.py, runs, and its tests pass:
"""Summaries of rain gauge readings."""
from rainkit.stats import Reading
def station_total(readings: list[Reading], station: str) -> float | None:
"""Return a station's total rainfall, rounded to 0.1 mm, or None if it has no readings."""
total = 0.0
found = False
for reading in readings:
if reading.station == station:
total += reading.rain_mm
found = True
if found == False:
return None
rounded = round(total, 1)
return total
def station_names(readings: list[Reading]) -> list[str]:
"""Return the names of the stations, each once, in alphabetical order."""
names = []
for reading in readings:
if not reading.station in names:
names.append(reading.station)
return sorted(names)Ruff reports:
src/rainkit/summary.py:14:8: E712 Avoid equality comparisons to `False`; use `not found:` for false checks
src/rainkit/summary.py:16:5: F841 Local variable `rounded` is assigned to but never used
src/rainkit/summary.py:24:16: E713 [*] Test for membership should be `not in`
Found 3 errors.
[*] 1 fixable with `--fix` (2 unsafe fixes available with `--fix --unsafe-fixes`).Which finding is a bug, and what does
station_totalreturn for two readings at Hilltop of 0.1 and 0.2 mm?Fix all three by hand. Then make
station_namesshorter with a set, which keeps each name once.
Hint
What does the function return, and what was it meant to return? Try 0.1 + 0.2 in Python.
Answer
F841 is the bug. The function rounds the total into
rounded, then returnstotal, so the docstring’s promise is broken: for 0.1 and 0.2 mm it returns0.30000000000000004instead of0.3. A variable that is assigned and never read often means code that uses the wrong variable. The tests passed because none of them used values that floating-point arithmetic can’t store exactly.def station_total(readings: list[Reading], station: str) -> float | None: """Return a station's total rainfall, rounded to 0.1 mm, or None if it has no readings.""" total = 0.0 found = False for reading in readings: if reading.station == station: total += reading.rain_mm found = True if not found: return None return round(total, 1) def station_names(readings: list[Reading]) -> list[str]: """Return the names of the stations, each once, in alphabetical order.""" return sorted({reading.station for reading in readings})E712:
found == Falseworks, butnot foundsays the same thing directly, as PEP 8 recommends. E713:not reading.station in namesreads as “(not reading.station) in names” to many people;reading.station not in namescan’t be misread. The set comprehension keeps each name once, andsortedturns it into a list in alphabetical order, which is what the return type promises.
Exercise 18.4 (LO-18.2, ★★, about 15 minutes)¶
Another new module, src/rainkit/days.py, passes Ruff. mypy, in strict mode, doesn’t pass it:
"""Dates and running totals."""
from datetime import date
def parse_day(text: str) -> date:
"""Return the date in text, such as "2026-11-02", or None if it isn't a date."""
try:
return date.fromisoformat(text)
except ValueError:
print(f"not a date: {text}")
def sorted_stations(totals: dict[str, float]) -> list[str]:
"""Return the names of the stations in totals, in alphabetical order."""
return {name for name in sorted(totals)}
def add_reading(totals: dict[str, float], station: str, rain_mm: float) -> None:
"""Add a reading to its station's total; the station must already be in totals."""
totals[station] = totals.get(station) + rain_mmsrc/rainkit/days.py:6: error: Missing return statement [return]
src/rainkit/days.py:16: error: Incompatible return value type (got "set[str]", expected "list[str]") [return-value]
src/rainkit/days.py:21: error: Unsupported operand types for + ("None" and "float") [operator]
src/rainkit/days.py:21: note: Left operand is of type "float | None"
Found 3 errors in 1 file (checked 1 source file)For each error, say what would go wrong when the code runs, and fix it without # type: ignore.
Hint
When a function reaches its end without a return, it returns None. What order does a set keep? What does dict.get return for a key that isn’t there?
Answer
def parse_day(text: str) -> date | None:
"""Return the date in text, such as "2026-11-02", or None if it isn't a date."""
try:
return date.fromisoformat(text)
except ValueError:
print(f"not a date: {text}")
return None
def sorted_stations(totals: dict[str, float]) -> list[str]:
"""Return the names of the stations in totals, in alphabetical order."""
return sorted(totals)
def add_reading(totals: dict[str, float], station: str, rain_mm: float) -> None:
"""Add a reading to its station's total; the station must already be in totals."""
totals[station] += rain_mmLine 6: after
except, the function falls off its end and returnsNone, which its hint says can’t happen, so callers would useNoneas a date. The hint becomesdate | None, as the docstring says, and thereturn Noneis written out: mypy reports a missing return statement even whenNoneis allowed, so that returningNoneis always a decision someone made.Line 16: the set comprehension throws away the order
sortedmade, because a set has no order you can rely on, and callers expecting a list would get a set.sortedalready returns a list of the keys.Line 21:
totals.get(station)returnsNonefor a station that isn’t there, andNone + 2.5raisesTypeError. The docstring says the station must be there, sototals[station] += rain_mmsays so in code: a missing station raisesKeyError, which names it. If missing stations should start from zero instead,totals.get(station, 0.0) + rain_mmdoes that, and the docstring must change to match.
Exercise 18.5 (LO-18.3, ★, about 10 minutes)¶
rainkit is at version 1.1.0. Since then, three commits have been made:
“Round totals to two decimal places instead of one.”
“Stop counting a reading twice when the CSV file repeats a line.”
“Rewrite
dry_daysas a list comprehension.”
What is the next version, and what goes in its changelog entry? Remember that rainkit’s output is part of its public interface: other programs read it.
Answer
2.0.0. The first commit changes the output: a program that reads rainkit’s totals, or a test that compares them, now gets a different number, such as 8.62 where it got 8.6, so it is a breaking change, and MAJOR goes up. The second is a bug fix and the third changes nothing for users; on their own they would have made 1.1.1 and no release at all.
## [2.0.0] - 2026-12-05
### Changed
- Totals are rounded to two decimal places instead of one. Programs that read rainkit's output
will see the extra digit.
### Fixed
- A reading that appears twice in a CSV file is counted once.The rewrite of dry_days stays out: the changelog is for users, and the Git history already records it. Saying plainly what a breaking change breaks lets users decide whether to upgrade.
Exercise 18.6 (LO-18.1, LO-18.2, LO-18.3, ★★★, about 25 minutes)¶
Publish rainkit on GitHub, with its checks, and release it:
Make
m18/rainkita Git repository with a.gitignorefor__pycache__/, add the MIT License’s text toLICENSEwith the year and your name, and add the reading’srequirements-dev.txt,CHANGELOG.md, and.github/workflows/checks.yml. Commit everything, create an empty repository on GitHub, and push, as in Module 10.On GitHub, open the Actions tab, and wait for the Checks run to pass.
Break the formatting on purpose: in
stats.py, changetotals.get(reading.station, 0.0)tototals.get(reading.station,0.0). Run the tests on your computer (they pass), then commit and push. Which step fails on GitHub, and what does its log say?Fix it with
python -m ruff format, commit, and push. When the run passes, release 1.0.0 as the reading’s steps say, and push the tag.
Hint
The workflow’s steps run in order, and a failed step skips the ones after it (Module 13). git tag -n lists your tags; git ls-remote --tags origin lists the tags GitHub has.
Answer
The commands are Module 10’s:
git init,git add .,git commit -m "...", thengit remote add origin <the repository's URL>andgit push -u origin main. Checkgit statusbefore the commit: the caches and__pycache__folders shouldn’t be listed.The run shows each step with a green check mark: Install rainkit and the tools, Lint, Check the formatting, Check the types, and Run the tests, after GitHub’s own steps and the checkout and setup.
Lint passes, because none of the rules this project selects is about the space after a comma: that is the formatter’s job. Check the formatting fails. Its log shows the line
ruff formatwould change, then a line that starts1 file would be reformatted, and thenProcess completed with exit code 1.The steps after it, Check the types and Run the tests, are skipped. The tests passing on your computer proved nothing about the formatting, which is why the workflow runs every check.python -m ruff formatprints a line that starts1 file reformatted. After the release,git tag -nshowsv1.0.0 rainkit 1.0.0, and the repository’s page on GitHub lists the tag. Runpython -m ruff formatbefore every commit, and this step never fails.