Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Module 18: Packaging and quality tools

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:

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.py

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 0

action="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.8

README.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:

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.0

An 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.csv

macOS and Linux:

../../.venv/bin/rainkit rain.csv
Harbor        8.6 mm
Hilltop      13.3 mm

python -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 pytest

Both tests pass. Two lines in the header at the top of pytest’s report are new:

rootdir: /home/ada/py101/m18/rainkit
configfile: pyproject.toml

pytest 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.

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 concise
src/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:

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 concise
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`
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 reformatted

Lines 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 = true

By 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 src
src/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:

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 0

Put 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 0

After 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 files

And 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:

Each increase sets the numbers after it to zero, and each number is compared as a whole number:

Current versionThe releaseNext version
1.4.2Fixes a rounding error in the totals1.4.3
1.4.2Adds a --json option1.5.0
1.4.2Renames the option --from to --start2.0.0
1.9.0Adds an option1.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.

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:

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.1

Without 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 pytest

The 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:

  1. Run every check: python -m ruff check, python -m ruff format --check, python -m mypy src, and python -m pytest. Each one passes.

  2. Set version = "1.0.0" in pyproject.toml, and install again with python -m pip install -e .. rainkit --version now prints rainkit 1.0.0.

  3. In CHANGELOG.md, move the entries under ## [Unreleased] to a new heading, ## [1.0.0] - and the date.

  4. Commit the release, and push:

    git add pyproject.toml CHANGELOG.md
    git commit -m "Release 1.0.0"
    git push

    Wait for the Checks workflow to pass on GitHub.

  5. Tag the commit, and push the tag. git push doesn’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.0

After 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

MisconceptionWhat’s trueAn example that breaks it
An editable install copies my code into the environmentIt points the environment at src, so code changes take effect at once; changes to pyproject.toml need another installAfter version = "0.2.0", rainkit --version prints 0.1.0 until you install again
Code that passes Ruff is correctRuff finds patterns that are often mistakes; it doesn’t know what the code should doThe Ruff-clean report.py still had two errors that mypy found
# noqa or # type: ignore fixes a findingIt hides the finding and keeps the problemWith # type: ignore[union-attr], mypy passes and rainkit still crashes on a file with no readings
ruff format and ruff check do the same jobformat changes only the layout; check finds problems, and fixes some of themruff format keeps an unused import os, which ruff check reports as F401
Version 1.10.0 comes before 1.9.0Each number is compared as a whole number1.10.0 is newer, because 10 is more than 9
A tag moves forward with new commits, as a branch doesA tag stays on the commit it namesAfter another commit, main is on the new commit and v1.0.0 is still on the release

Summary

Self-check

  1. A project’s pyproject.toml has wordtally = "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 module wordtally.cli and calls its function run, and the command’s exit status is whatever run returns. (pip writes a small program that calls sys.exit(run()).)

  2. With rainkit installed in editable mode, you change total_by_station to round to two decimal places, and change description in pyproject.toml. Which change shows up without installing again?

    Answer

    Only the change to total_by_station. An editable install points at the code in src, so the next run uses it; the description is part of the package’s details, which pip recorded when it installed the package.

  3. Ruff reports B006 for def add(item, basket=[]):, whose body runs basket.append(item) and returns basket. 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 basket appends to the same list: add(1) returns [1], and a second add(2) returns [1, 2]. Use None as the default, and make a new list in the body:

    def add(item, basket=None):
        if basket is None:
            basket = []
        basket.append(item)
        return basket

  4. rainkit is at version 1.4.2. The next release adds a --json option 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.

  5. Why does requirements-dev.txt pin ruff==0.17.6 instead of listing ruff?

    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