Objectives: LO-18.1, LO-18.2, LO-18.3
Prerequisites: Module 9,
Module 10,
Module 13, and
Module 14, and Ruff and mypy from Setting up your
computer
Time: about 5.5 hours: 2 for this reading, 2 for Lab 18, and 1.5 for the
practice
This module turns a project into something other people can install and use. You make it a package that pip installs with one command, and that gives its users a command of its own, as pytest does. Then you add two tools that check code before it runs: Ruff, which finds common mistakes and lays out code in one consistent style, and mypy, which checks type hints. The module ends with releasing a version: a version number that means something, a changelog, a license, a Git tag, and a workflow that runs every check on GitHub.
The example is rainkit, a small tool that adds up rain gauge readings. Work in a new folder,
m18, in your py101 folder, and make the project in m18/rainkit. As in Module 17, python
in a command stands for your environment’s Python, run by its path.
A project as a package¶
Why a package¶
Since Module 9, your programs have been scripts: files you run with python weather.py, which
import the modules beside them. That works while you run them from their own folder, but it
breaks in three ways as a project grows:
Python finds
import statsonly whenstats.pyis in a folder on its search path (Module 9), so the script fails when you run it from anywhere else.Anyone else who wants your program needs your files, your folder layout, and instructions for running them.
Nothing records the program’s version, the Python it needs, or the packages it depends on.
An installable package solves all three. It is a folder of modules that Python imports by
name, such as rainkit.stats, together with a file that tells pip how to install it: its name,
its version, the Python it needs, its dependencies, and the commands it provides. Once it is
installed in an environment, its modules import from any folder and its command runs from any
folder, as pytest’s does.
The src layout¶
Make this tree of files. The rest of this section gives each file’s contents:
rainkit/
├── pyproject.toml
├── README.md
├── LICENSE
├── rain.csv
├── src/
│ └── rainkit/
│ ├── __init__.py
│ ├── __main__.py
│ ├── cli.py
│ └── stats.py
└── tests/
└── test_stats.pyThe outer
rainkitfolder is the project: everything you keep in its Git repository.src/rainkitis the package: the code that gets installed. A folder with an__init__.pyfile is a package, and the modules in it are imported asrainkit.statsandrainkit.cli.pyproject.tomldescribes the project to pip and to the tools that check it.The tests sit outside the package, because users don’t need them.
Putting the package in a folder named src, instead of at the top of the project, is called the
src layout. When you run python -m pytest in the project’s folder, Python adds that folder
to its search path. With the package at the top, the tests would import your working copy
straight from the folder, whether or not the package installs correctly. Inside src, the only
way to import rainkit is to install it, so the tests test what your users will get. The
Python Packaging User Guide recommends this layout for that reason.
The package’s code¶
stats.py reads the readings from a CSV file (Module 11) into dataclasses (Module 14), and adds
them up:
"""Read rain gauge readings, and add them up."""
import csv
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True)
class Reading:
"""One day's rainfall at one station."""
station: str
day: str
rain_mm: float
def read_readings(path: Path) -> list[Reading]:
"""Read the readings in a CSV file with the columns station, day, and rain_mm."""
with open(path, newline="", encoding="utf-8") as file:
return [
Reading(row["station"], row["day"], float(row["rain_mm"]))
for row in csv.DictReader(file)
]
def total_by_station(readings: list[Reading]) -> dict[str, float]:
"""Return each station's total rainfall, in alphabetical order of station."""
totals: dict[str, float] = {}
for reading in readings:
totals[reading.station] = totals.get(reading.station, 0.0) + reading.rain_mm
return {station: round(totals[station], 1) for station in sorted(totals)}cli.py is the command-line program, with argparse (Module 9). Its main takes the arguments
as a list, so a test can pass them in; with no list, argparse reads sys.argv. It returns the
exit status instead of calling sys.exit itself:
"""The rainkit command."""
import argparse
import sys
from pathlib import Path
from rainkit import __version__
from rainkit.stats import read_readings, total_by_station
def main(argv: list[str] | None = None) -> int:
"""Print each station's total rainfall, and 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("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
for station, total in total_by_station(readings).items():
print(f"{station:<10} {total:6.1f} mm")
return 0action="version" prints the version and exits; argparse replaces %(prog)s with the
program’s name. The version comes from __init__.py, which runs the first time anything imports
from rainkit:
"""Add up rain gauge readings."""
from importlib.metadata import version
__version__ = version("rainkit")importlib.metadata.version reads the version of an installed package from the information pip
recorded when it installed it. So the version is written in one place only, pyproject.toml, and
the command can never report a different one.
__main__.py lets you run the package with python -m rainkit, as you run python -m pytest:
"""Run the rainkit command with python -m rainkit."""
import sys
from rainkit.cli import main
sys.exit(main())The test file is ordinary pytest (Module 13). It imports from rainkit.stats, as a user’s code
would:
from rainkit.stats import Reading, read_readings, total_by_station
def test_total_by_station():
readings = [
Reading("Hilltop", "2026-11-02", 3.1),
Reading("Harbor", "2026-11-02", 1.2),
Reading("Hilltop", "2026-11-03", 0.4),
]
assert total_by_station(readings) == {"Harbor": 1.2, "Hilltop": 3.5}
def test_read_readings(tmp_path):
path = tmp_path / "rain.csv"
path.write_text("station,day,rain_mm\nHarbor,2026-11-02,1.2\n", encoding="utf-8")
assert read_readings(path) == [Reading("Harbor", "2026-11-02", 1.2)]rain.csv holds a few days of readings to try the command on:
station,day,rain_mm
Harbor,2026-11-02,1.2
Hilltop,2026-11-02,3.1
Harbor,2026-11-03,0.0
Hilltop,2026-11-03,0.4
Harbor,2026-11-04,7.4
Hilltop,2026-11-04,9.8README.md starts as a title and the one-sentence description. LICENSE holds the license’s
text, which “Releasing a version” explains; until then, leave the file empty.
pyproject.toml¶
pyproject.toml is written in TOML, a format for settings files. A line in square brackets,
such as [project], starts a table, a named group of settings, and each line after it sets one
key = value. Strings go in double quotation marks and lists in square brackets, as in Python.
This is rainkit’s:
[build-system]
requires = ["hatchling >= 1.26"]
build-backend = "hatchling.build"
[project]
name = "rainkit"
version = "0.1.0"
description = "Add up rain gauge readings from a CSV file."
readme = "README.md"
requires-python = ">=3.12"
license = "MIT"
license-files = ["LICENSE"]
dependencies = []
[project.scripts]
rainkit = "rainkit.cli:main"Table by table:
[build-system]names the build backend: the package that turns the project’s folder into something pip can install. pip doesn’t build packages itself; it downloads the backend named inrequiresand asks it to. This project uses Hatchling, as the Packaging Guide’s tutorial does. The first install downloads it from PyPI (the Python Package Index, where pip finds packages), so you need an internet connection.[project]describes the package:nameis what pip andimportlib.metadatacall it, andversionis its version number, which “Releasing a version” explains.readmenames the file with its long description.requires-pythonstops pip from installing it into a Python older than 3.12.licensenames the license, andlicense-fileslists the files with its text.dependencieslists the packages from PyPI that it needs, in the same form as a requirements file, such as"matplotlib >= 3.11". rainkit needs only the standard library, so the list is empty.
[project.scripts]creates commands.rainkit = "rainkit.cli:main"makes a command namedrainkitthat imports the modulerainkit.cliand calls itsmainfunction. The part before the colon is a module; the part after it is a function in that module.
Installing in editable mode¶
From the rainkit folder, install the project into your course environment:
python -m pip install -e .The . is the current folder, and -e makes it an editable install. pip prints a few lines
about building the package, and ends with:
Successfully installed rainkit-0.1.0An editable install doesn’t copy your code into the environment. It points the environment at
your src folder, so when you change stats.py, the next run uses the change. What pip copies
are the package’s details from pyproject.toml: its name, its version, and its commands. Change
those, and you must install again. If version becomes "0.2.0", rainkit --version keeps
printing 0.1.0 until you run the same pip install -e . again.
The install also wrote the rainkit command into your environment, beside python. Run it by its
path, from the rainkit folder.
Windows:
..\..\.venv\Scripts\rainkit rain.csvmacOS and Linux:
../../.venv/bin/rainkit rain.csvHarbor 8.6 mm
Hilltop 13.3 mmpython -m rainkit rain.csv prints the same, through __main__.py. From here on, rainkit in
a command stands for the command, run by its path. rainkit --version prints rainkit 0.1.0.
The command handles its own errors, as a command-line program should (Module 12):
rainkit nowhere.csv prints this line and exits with status 1:
rainkit: can't read nowhere.csv: [Errno 2] No such file or directory: 'nowhere.csv'With no file name at all, argparse prints the usage and exits with status 2.
Now the tests run from the project’s folder, against the installed package:
python -m pytestBoth tests pass. Two lines in the header at the top of pytest’s report are new:
rootdir: /home/ada/py101/m18/rainkit
configfile: pyproject.tomlpytest found pyproject.toml and uses the project’s folder as its rootdir, wherever in the
project you run it. In an environment where rainkit isn’t installed, the same command fails before
running a test, which is the src layout doing its job:
E ModuleNotFoundError: No module named 'rainkit'python -m pip uninstall rainkit removes the package and its command from the environment, and
leaves your files alone.
Checking code with Ruff¶
What a linter finds¶
A linter reads code without running it and reports patterns that are often mistakes: an import
nothing uses, a variable that is never read, an except that catches everything. Ruff is a fast
linter for Python, and also a formatter, which rewrites code into one consistent layout. Ruff
reimplements the rules of several older tools, and keeps their codes: F401 comes from the tool
Pyflakes, and B006 from flake8-bugbear.
Ruff reads its settings from pyproject.toml. Add these tables at the end of rainkit’s:
[tool.ruff]
line-length = 100
[tool.ruff.lint]
select = ["E", "F", "I", "B"]Every tool keeps its own settings under [tool.<name>], so one file configures the whole
project.
line-lengthis the longest line Ruff allows, and the width its formatter aims for. Ruff’s default is 88; this project allows 100.selectchooses the families of rules to check, by the first letters of their codes:Efor the style errors that PEP 8 describes, such as lines that are too long;Ffor problems Pyflakes finds, such as unused imports and undefined names;Ifor the order of imports; andBfor likely bugs from flake8-bugbear.selectreplaces Ruff’s default set of rules, which changes from release to release, so the project checks the same rules on every computer that has the same version of Ruff.
Reading Ruff’s report¶
Here is a first draft of a new module, src/rainkit/report.py, with three functions that answer
questions about readings. It runs, but it has problems:
import sys
import os
from rainkit.stats import Reading, total_by_station
import json
def wettest(readings: list[Reading]) -> Reading:
"""Return the reading with the most rain."""
if readings == []:
return None
best = readings[0]
for r in readings:
if r.rain_mm > best.rain_mm:
best = r
return best
def dry_days(readings, stations=[]):
"""Return the readings with no rain, at the given stations or at all of them."""
l = []
for reading in readings:
if reading.rain_mm == 0 and (stations == [] or reading.station in stations):
l.append(reading)
return l
def save_totals(readings: list[Reading], path: str) -> None:
"""Write each station's total rainfall to a JSON file."""
try:
with open(path, "w", encoding="utf-8") as file:
json.dump(total_by_station(readings), file)
except:
print(f"could not save the totals", file=sys.stderr)Run Ruff from the project’s folder. check looks at every Python file under the current folder,
and --output-format concise prints one line for each finding:
python -m ruff check --output-format concisesrc/rainkit/report.py:1:1: I001 [*] Import block is un-sorted or un-formatted
src/rainkit/report.py:2:8: F401 [*] `os` imported but unused
src/rainkit/report.py:18:33: B006 Do not use mutable data structures for argument defaults
src/rainkit/report.py:20:5: E741 Ambiguous variable name: `l`
src/rainkit/report.py:32:5: E722 Do not use bare `except`
src/rainkit/report.py:33:15: F541 [*] f-string without any placeholders
Found 6 errors.
[*] 3 fixable with `--fix` (1 unsafe fix available with `--fix --unsafe-fixes`).Each line gives the file, the line, and the column, then the rule’s code and what it found. Without
--output-format concise, Ruff prints each finding with the lines around it and a suggested fix.
Each one is worth fixing:
I001: PEP 8 recommends putting the standard library’s imports first, then a blank line and the imports of the project’s own modules, and Ruff also sorts each group alphabetically. A reader then sees at a glance what the module depends on.
F401: nothing uses
os. An unused import is clutter at best, and at worst a sign that some code you meant to write is missing.B006:
stations=[]makes one list, once, when Python defines the function, and every call that leaves outstationsshares it. This function never changes the list, so it works today, but onestations.append(...)added later would leak values from one call into the next.E741:
llooks like1andIin many fonts. Here a name that says what the list holds would be clearer anyway.E722: a bare
except:catches every exception, including theKeyboardInterruptfrom Ctrl+C and theNameErrorfrom a typing mistake in thetryblock, and reports them all as a failure to save (Module 12).F541: an f-string with nothing to fill in is an ordinary string, and often a sign that the value you meant to include is missing, as it is here: the message doesn’t say what went wrong.
Fixing what Ruff found¶
[*] marks findings that Ruff can fix itself, safely. --fix makes those fixes and reports what
is left:
python -m ruff check --fix --output-format concisesrc/rainkit/report.py:18:33: B006 Do not use mutable data structures for argument defaults
src/rainkit/report.py:20:5: E741 Ambiguous variable name: `l`
src/rainkit/report.py:32:5: E722 Do not use bare `except`
Found 6 errors (3 fixed, 3 remaining).
1 unsafe fix available with `--fix --unsafe-fixes`.Ruff sorted the imports, removed os, and turned the f-string into an ordinary string. It leaves
the other three to you, because fixing them takes a decision: what to name the list, which
exceptions to catch, and how to replace the default. Ruff calls its fix for B006 “unsafe” because
it can change what the code does. Fix the three by hand, and give the message its missing detail:
def dry_days(readings, stations=None):
"""Return the readings with no rain, at the given stations or at all of them."""
found = []
for reading in readings:
if reading.rain_mm == 0 and (stations is None or reading.station in stations):
found.append(reading)
return found
def save_totals(readings: list[Reading], path: str) -> None:
"""Write each station's total rainfall to a JSON file."""
try:
with open(path, "w", encoding="utf-8") as file:
json.dump(total_by_station(readings), file)
except OSError as error:
print(f"could not save the totals: {error}", file=sys.stderr)OSError is what open and writing raise when a file can’t be written (Module 12), so it is the
one failure this function knows how to report. Run Ruff again:
All checks passed!You can silence a finding instead, with a comment such as # noqa: E741 at the end of its line,
which tells Ruff to skip that rule there. Don’t, unless the rule is wrong for that one line, and
then say why in the comment. A silenced finding is a problem you still have, now hidden from
everyone who reads the report.
Formatting with Ruff¶
A formatter decides the layout that people argue about: spaces, quotation marks, blank lines, and
where long lines break. Running one on every file gives the whole project one style, so a change
to the code is never mixed with someone’s change to the spacing. Take this badly laid out file,
messy.py:
import json
def ratio(a,b):
return {'a':a/b, 'b':b/a}
rows=[1,2,
3]
print( json.dumps(ratio(3,4)) )ruff format --diff shows what the formatter would change, without changing anything:
python -m ruff format --diff messy.py--- messy.py
+++ messy.py
@@ -1,6 +1,9 @@
import json
-def ratio(a,b):
- return {'a':a/b, 'b':b/a}
-rows=[1,2,
- 3]
-print( json.dumps(ratio(3,4)) )
+
+
+def ratio(a, b):
+ return {"a": a / b, "b": b / a}
+
+
+rows = [1, 2, 3]
+print(json.dumps(ratio(3, 4)))
1 file would be reformattedLines starting with - are removed and lines starting with + added: two blank lines around the
function, spaces after commas and around operators, double quotation marks, and the list joined
onto one line because it fits. python -m ruff format with no file name formats every file in the
project. python -m ruff format --check changes nothing: it shows what it would change in each
file, and exits with status 1 if there is anything to change. The formatter changes layout only:
it never removes an unused import or renames a variable. That is ruff check’s job.
Ruff and mypy keep caches of earlier results in .ruff_cache and .mypy_cache. Each cache folder
holds its own .gitignore file, so Git ignores them without a line in yours.
Checking types with mypy¶
Strict mode¶
Module 14 showed mypy finding the type errors in one file. A project runs it on the whole
package, with its settings in pyproject.toml:
[tool.mypy]
strict = trueBy default, mypy skips the inside of any function that has no type hints, so code without hints
gets no checks at all. Strict mode turns on a group of extra checks, among them one that
reports every function without hints. Then nothing escapes the checks. The mypy documentation
calls passing in strict mode “an excellent goal” for a codebase, and a new project can start
there. Run mypy on the src folder:
python -m mypy srcsrc/rainkit/report.py:10: error: Incompatible return value type (got "None", expected "Reading") [return-value]
src/rainkit/report.py:18: error: Function is missing a type annotation [no-untyped-def]
Found 2 errors in 1 file (checked 5 source files)Ruff passed this file, and mypy finds two more problems in it:
Line 10:
wettestpromises to return aReading, but returnsNonefor an empty list. A caller who trusts the hint will crash on thatNone.Line 18:
dry_dayshas no hints, so its callers get no checks. Strict mode insists.
Fixing what mypy found¶
Make the hints say what the functions really do. This is the finished report.py, with a
docstring for the module, and two functions written more briefly:
"""Questions about rain gauge readings."""
import json
import sys
from rainkit.stats import Reading, total_by_station
def wettest(readings: list[Reading]) -> Reading | None:
"""Return the reading with the most rain, or None if there are no readings."""
if not readings:
return None
return max(readings, key=lambda reading: reading.rain_mm)
def dry_days(readings: list[Reading], stations: set[str] | None = None) -> list[Reading]:
"""Return the readings with no rain, at the given stations or at all of them."""
return [
reading
for reading in readings
if reading.rain_mm == 0 and (stations is None or reading.station in stations)
]
def save_totals(readings: list[Reading], path: str) -> None:
"""Write each station's total rainfall to a JSON file."""
try:
with open(path, "w", encoding="utf-8") as file:
json.dump(total_by_station(readings), file)
except OSError as error:
print(f"could not save the totals: {error}", file=sys.stderr)mypy now prints Success: no issues found in 5 source files. The new hint on wettest matters
most when someone calls it. Add the wettest day to the command’s output: in cli.py, import the
function, and print its result after the totals:
from rainkit.report import wettest for station, total in total_by_station(readings).items():
print(f"{station:<10} {total:6.1f} mm")
best = wettest(readings)
print(f"Wettest: {best.station} on {best.day}")
return 0Put the import with the other rainkit imports, in alphabetical order, as Ruff’s I rules
expect. mypy reports the new lines:
src/rainkit/cli.py:26: error: Item "None" of "Reading | None" has no attribute "station" [union-attr]
src/rainkit/cli.py:26: error: Item "None" of "Reading | None" has no attribute "day" [union-attr]
Found 2 errors in 1 file (checked 5 source files)rain.csv has readings, so the command works on it, and a test with that file would pass. But a
CSV file with a header and no readings makes wettest return None, and the command crashes. Fix
it by checking for None first:
best = wettest(readings)
if best is not None:
print(f"Wettest: {best.station} on {best.day}")
return 0After if best is not None:, mypy knows that best is a Reading inside the if block, so the
errors go away. Checking a value narrows its type in this way. The command now prints
Wettest: Hilltop on 2026-11-04 after the totals for rain.csv, and nothing more for a file with
no readings.
As with Ruff, you can silence mypy, with # type: ignore[union-attr] at the end of the line.
Here is what that does:
Success: no issues found in 5 source filesAnd here is the last line of the traceback when the command runs on the file with no readings:
AttributeError: 'NoneType' object has no attribute 'station'mypy is quiet, and the crash is still there. A type error is a description of a crash that hasn’t happened yet: fix the code, not the report.
Releasing a version¶
A release is a version of the project that you give a number and tell people about. Users
install a release, not whatever is on your main branch today, so a release needs a version
number that tells them what changed, a list of the changes, a license that says what they may do
with it, and evidence that its checks passed.
Version numbers¶
Most Python packages use semantic versioning: a version is three numbers,
MAJOR.MINOR.PATCH, and which number goes up says what kind of change the release makes for its
users. From the current version, increase:
MAJOR when the release breaks something users relied on: a removed or renamed option, a changed output format, a function that now takes different arguments;
MINOR when it adds something new, and everything that worked before still works the same;
PATCH when it only fixes bugs, and changes nothing that worked as documented.
Each increase sets the numbers after it to zero, and each number is compared as a whole number:
| Current version | The release | Next version |
|---|---|---|
| 1.4.2 | Fixes a rounding error in the totals | 1.4.3 |
| 1.4.2 | Adds a --json option | 1.5.0 |
| 1.4.2 | Renames the option --from to --start | 2.0.0 |
| 1.9.0 | Adds an option | 1.10.0, which is newer than 1.9.0 |
What counts as “something users relied on” is the project’s public interface: for rainkit, the command’s options, its output, and its exit statuses. Semantic versioning treats versions before 1.0.0 as early development, in which anything may change at any time. Releasing 1.0.0 says that the public interface is settled, and that from then on a breaking change will raise the major number.
A changelog¶
A changelog is a file, CHANGELOG.md, that lists the notable changes in each release, newest
first, for the people who use the project. The Git history is a record for its developers, and
holds every commit; a user upgrading from 0.1.0 wants to know what changed for them. rainkit’s
changelog follows the format of Keep a Changelog 1.1.0:
# Changelog
The notable changes to rainkit, newest first. The format follows
[Keep a Changelog 1.1.0](https://keepachangelog.com/en/1.1.0/), and rainkit uses
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [1.0.0] - 2026-12-04
### Added
- After the totals, `rainkit` prints the day with the most rain.
## [0.1.0] - 2026-11-30
### Added
- The `rainkit` command, which prints each station's total rainfall from a CSV file.Each release has a heading with its version and its date, in the form
2026-12-04.Under it, the changes are sorted under
### Added,### Changed,### Deprecated(still there, but going away),### Removed,### Fixed, and### Security, using only the headings a release needs.## [Unreleased]collects changes as you make them. At a release, they move under the new version’s heading.Each entry says what changed for a user, not how the code changed.
A license¶
Without a license, copyright law in most countries keeps every right to your code with you, and nobody else may copy, change, or share it. Publishing it in a public repository lets others only view it and fork it on GitHub, under GitHub’s terms of service. A license gives others those rights, on its conditions. GitHub’s choosealicense.com compares the common open-source licenses in plain language. Two examples:
The MIT License lets anyone use, copy, change, and share the code, in their own projects too, as long as they keep the copyright notice and the license’s text. This course’s code uses it.
The GNU GPLv3 allows the same, but requires anyone who shares a changed version to share its source code under the same license.
To use the MIT License, copy its text from its page on
choosealicense.com into LICENSE, and put the year and
your name in its copyright line. Then pyproject.toml names it twice: license = "MIT" gives
its standard short name, from the SPDX license list, and
license-files = ["LICENSE"] includes its text in the package.
Checks on every push¶
Module 13’s workflow ran the tests on every push. A project runs every check there, at the same
versions you run on your computer. Pin the tools in a new file, requirements-dev.txt: the
packages a developer of the project needs, which its users don’t:
pytest==9.2.0
ruff==0.17.6
mypy==2.4.1Without the pins, a new release of Ruff with a new rule, or a small change to its formatting, could fail the workflow on code that hasn’t changed. With them, upgrading a tool is a change you make on purpose, in a commit of its own.
Then save the workflow as .github/workflows/checks.yml:
name: "Checks"
on: [push]
jobs:
check:
runs-on: ubuntu-latest
steps:
- name: "Check out the repository"
uses: actions/checkout@v7
- name: "Set up Python"
uses: actions/setup-python@v7
with:
python-version: "3.12"
- name: "Install rainkit and the tools"
run: python -m pip install -r requirements-dev.txt -e .
- name: "Lint"
run: python -m ruff check
- name: "Check the formatting"
run: python -m ruff format --check
- name: "Check the types"
run: python -m mypy src
- name: "Run the tests"
run: python -m pytestThe first three steps are Module 13’s, with -e . added to the install, so the tests import the
installed package. Each check is a step of its own, so the run’s page shows which one failed, and
each one ends with exit status 1 when it finds a problem, which fails the step and the run.
ruff format --check matters here: it fails when a file isn’t formatted, so you run
python -m ruff format before you commit.
Tagging the release¶
A tag is a name for one commit, such as v1.0.0. A branch moves forward with each new commit;
a tag stays where you put it, so v1.0.0 always means exactly the code you released. To release
rainkit 1.0.0, from its folder:
Run every check:
python -m ruff check,python -m ruff format --check,python -m mypy src, andpython -m pytest. Each one passes.Set
version = "1.0.0"inpyproject.toml, and install again withpython -m pip install -e ..rainkit --versionnow printsrainkit 1.0.0.In
CHANGELOG.md, move the entries under## [Unreleased]to a new heading,## [1.0.0] -and the date.Commit the release, and push:
git add pyproject.toml CHANGELOG.md git commit -m "Release 1.0.0" git pushWait for the Checks workflow to pass on GitHub.
Tag the commit, and push the tag.
git pushdoesn’t send tags, so name it:git tag -a v1.0.0 -m "rainkit 1.0.0" git push origin v1.0.0
-a makes an annotated tag, which records who made it, when, and a message, as a commit does;
use one for every release. git tag -n lists the tags with their messages:
v1.0.0 rainkit 1.0.0After the next commit, git log --oneline --decorate shows main on the new commit and the tag
still on the release, so anyone can check out exactly the code of 1.0.0 with
git switch --detach v1.0.0.
This course stops at a release on GitHub. Publishing a package on PyPI, so that anyone can install
it with pip install and its name, takes two more tools and an account, and the Packaging
Guide’s tutorial walks through it, starting with a practice version of PyPI called TestPyPI.
Common misconceptions¶
| Misconception | What’s true | An example that breaks it |
|---|---|---|
| An editable install copies my code into the environment | It points the environment at src, so code changes take effect at once; changes to pyproject.toml need another install | After version = "0.2.0", rainkit --version prints 0.1.0 until you install again |
| Code that passes Ruff is correct | Ruff finds patterns that are often mistakes; it doesn’t know what the code should do | The Ruff-clean report.py still had two errors that mypy found |
# noqa or # type: ignore fixes a finding | It hides the finding and keeps the problem | With # type: ignore[union-attr], mypy passes and rainkit still crashes on a file with no readings |
ruff format and ruff check do the same job | format changes only the layout; check finds problems, and fixes some of them | ruff format keeps an unused import os, which ruff check reports as F401 |
| Version 1.10.0 comes before 1.9.0 | Each number is compared as a whole number | 1.10.0 is newer, because 10 is more than 9 |
| A tag moves forward with new commits, as a branch does | A tag stays on the commit it names | After another commit, main is on the new commit and v1.0.0 is still on the release |
Summary¶
An installable package keeps its code in
src/<name>, with__init__.py, and describes itself inpyproject.toml: the build backend in[build-system], its name, version, Python, license, and dependencies in[project], and its commands in[project.scripts], asname = "module:function".python -m pip install -e .installs a project in editable mode: code changes take effect at once, and changes topyproject.tomlneed another install.__main__.pymakespython -m <name>work, andimportlib.metadata.versionreads the installed version.Ruff’s
checkfinds likely mistakes by rule,--fixfixes the safe ones, andformatlays code out in one style. mypy’s strict mode checks every function’s type hints. Fix each finding, rather than silencing it with# noqaor# type: ignore.Semantic versioning raises MAJOR for a breaking change, MINOR for a new feature, and PATCH for a bug fix. A changelog lists each release’s changes for users, and a license says what others may do with the code.
A release runs every check, sets the version, updates the changelog, commits, and adds an annotated tag, such as
v1.0.0. A workflow runs Ruff, mypy, and pytest on every push, with the tools pinned inrequirements-dev.txt.
Self-check¶
A project’s
pyproject.tomlhaswordtally = "wordtally.cli:run"under[project.scripts]. What does a user type to start it once it’s installed, and what does that do?Answer
They type
wordtally, with its arguments. The command imports the modulewordtally.cliand calls its functionrun, and the command’s exit status is whateverrunreturns. (pip writes a small program that callssys.exit(run()).)With rainkit installed in editable mode, you change
total_by_stationto round to two decimal places, and changedescriptioninpyproject.toml. Which change shows up without installing again?Answer
Only the change to
total_by_station. An editable install points at the code insrc, so the next run uses it; the description is part of the package’s details, which pip recorded when it installed the package.Ruff reports
B006fordef add(item, basket=[]):, whose body runsbasket.append(item)and returnsbasket. What goes wrong, and how do you fix it?Answer
The default list is made once, when Python defines the function, so every call without a
basketappends to the same list:add(1)returns[1], and a secondadd(2)returns[1, 2]. UseNoneas the default, and make a new list in the body:def add(item, basket=None): if basket is None: basket = [] basket.append(item) return basketrainkit is at version 1.4.2. The next release adds a
--jsonoption and fixes a bug in reading files with blank lines. What is its version, and under which changelog headings do the two changes go?Answer
1.5.0: the new option is a new feature that breaks nothing, which raises MINOR and sets PATCH to zero; the bug fix alone would have made 1.4.3. The option goes under
### Added, and the bug fix under### Fixed.Why does
requirements-dev.txtpinruff==0.17.6instead of listingruff?Answer
A new Ruff release can add rules or change how it formats code, so an unpinned workflow could start failing on code nobody changed, and two developers could get different results. With the pin, everyone runs the same checks, and upgrading Ruff is a deliberate change, made and reviewed in its own commit.
Further reading¶
The Python Packaging User Guide’s tutorial Packaging Python Projects and its guide Writing your pyproject.toml. The tutorial this module’s
pyproject.tomlfollows, which goes on to publish on TestPyPI, and every field apyproject.tomlcan have.The Packaging Guide’s discussion src layout vs flat layout. The two layouts compared, and why the
srclayout catches packaging mistakes.Ruff’s rules, with a page for each rule that explains why it matters, such as mutable-argument-default (B006), and its pages on the linter and the formatter. Where to look up a finding you don’t understand.
The mypy documentation on the command line, which lists what
--strictturns on, and type narrowing. Howif best is not Noneworks, and the other checks mypy understands.Semantic Versioning 2.0.0 and Keep a Changelog 1.1.0. Both are short, and both answer the questions this module left out, such as how to number a release candidate.
Pro Git’s section Git Basics: Tagging. Annotated and lightweight tags, tagging an older commit, and sharing tags.