Objectives: LO-18.1, LO-18.2, LO-18.3
Prerequisites: the Module 18 reading, and Ruff and mypy installed in your course
environment, as Setting up your computer says
Time: about 2 hours
In this lab you turn wordtally, a small program that prints the most common words in a text
file, into a package: you write its pyproject.toml, install it, and run its command. Then you
fix what Ruff and mypy find in two of its modules, and release version 1.0.0 with a changelog,
a workflow that runs every check on GitHub, and a Git tag.
The project lives in scratch/lab18/wordtally. You write some of its files in cells that start
with %%writefile and a file name, as in Lab 13: running the cell saves the rest of the cell to
that file.
Installing the package takes about 15 seconds each time. The first time, pip also downloads the build backend, Hatchling, from PyPI, so you need an internet connection.
Setup¶
Run the next cell first. It checks that pip, Ruff, mypy, and Git are there, writes the project’s files, and defines these helpers:
run(*arguments)runspython -mand the arguments in the project’s folder, as a terminal in that folder would, and shows the output and the exit status.run("ruff", "check")ispython -m ruff check.install()installs the project in editable mode, aspython -m pip install -e .would, and shows pip’s last line.command(*arguments)runs thewordtallycommand that the install creates, by its path.load(name)imports one of the package’s modules afresh fromsrc, so the checks can call its functions.edit(name, old, new)changes one piece of a file in the project, andset_version(new)changes the version inpyproject.toml.git(command)runs a Git command in the project, as in Lab 10, andgit_output(command)returns what it printed.
import ast
import importlib
import importlib.util
import os
import re
import shlex
import shutil
import stat
import subprocess
import sys
import tomllib
from importlib.metadata import PackageNotFoundError, version
from pathlib import Path
import yaml
print("Python", sys.version.split()[0])
if importlib.util.find_spec("pip") is None:
raise RuntimeError("This environment has no pip. Make it as 'Setting up your computer' says.")
for tool in ["pip", "ruff", "mypy", "pytest"]:
try:
print(tool, version(tool))
except PackageNotFoundError:
raise RuntimeError(
f"{tool} isn't installed here. Install Ruff and mypy as 'Setting up your computer' "
"says in 'Before Module 18', then restart the kernel."
) from None
GIT = shutil.which("git")
if GIT is None:
raise RuntimeError("This notebook can't find Git. Install it as Module 10 describes.")
print(subprocess.run([GIT, "--version"], capture_output=True, text=True).stdout.strip())
SCRATCH = Path("scratch").absolute()
PROJECT = SCRATCH / "lab18" / "wordtally"
ENVIRONMENT = dict(
os.environ,
GIT_EDITOR=":",
GIT_TERMINAL_PROMPT="0",
GIT_CEILING_DIRECTORIES=str(SCRATCH),
GIT_AUTHOR_NAME="PY101 Learner",
GIT_AUTHOR_EMAIL="[email protected]",
GIT_COMMITTER_NAME="PY101 Learner",
GIT_COMMITTER_EMAIL="[email protected]",
)
OPTIONS = ["-c", "color.ui=never", "-c", "init.defaultBranch=main", "-c", "commit.gpgSign=false",
"-c", "tag.gpgSign=false"]
def remove(folder):
"""Delete folder and everything in it, including the files Git marks read-only."""
def make_writable_and_retry(function, path, error):
os.chmod(path, stat.S_IWRITE)
function(path)
if folder.exists():
shutil.rmtree(folder, onexc=make_writable_and_retry)
def write(name, text):
"""Write text to the file name in the project, making folders as needed."""
path = PROJECT / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
def read(name):
"""Return the text of the file name in the project."""
return (PROJECT / name).read_text(encoding="utf-8")
def run(*arguments, show=True):
"""Run python -m with arguments in the project's folder; return the output and exit status."""
result = subprocess.run(
[sys.executable, "-m", *arguments], cwd=PROJECT, timeout=300, text=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", errors="replace",
)
if show:
print(result.stdout, end="")
print(f"(exit status {result.returncode})")
return result.stdout, result.returncode
def settings():
"""Return pyproject.toml's settings as a dictionary, or {} if it doesn't parse."""
try:
return tomllib.loads(read("pyproject.toml"))
except (OSError, tomllib.TOMLDecodeError) as error:
print(f"pyproject.toml can't be read: {error}")
return {}
def install():
"""Install the project in editable mode; show pip's last line, and return the exit status."""
found = settings()
if "build-system" not in found or found.get("project", {}).get("name") != "wordtally":
print("pyproject.toml doesn't describe wordtally yet, so there is nothing to install.")
return None
print("Installing wordtally...")
output, status = run("pip", "install", "--disable-pip-version-check", "-e", ".", show=False)
print(output.strip().splitlines()[-1] if status == 0 else output)
return status
def command(*arguments, show=True):
"""Run the wordtally command with arguments; return its output and exit status."""
path = shutil.which("wordtally", path=str(Path(sys.executable).parent))
if path is None:
print("This environment has no wordtally command yet: the package isn't installed.")
return "", None
result = subprocess.run(
[path, *arguments], cwd=PROJECT, timeout=60, text=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", errors="replace",
)
if show:
print(result.stdout, end="")
print(f"(exit status {result.returncode})")
return result.stdout, result.returncode
def load(name):
"""Import wordtally.name afresh from the project's src folder, and return the module."""
source = str(PROJECT / "src")
if source not in sys.path:
sys.path.insert(0, source)
for module in [module for module in sys.modules if module.split(".")[0] == "wordtally"]:
del sys.modules[module]
importlib.invalidate_caches()
return importlib.import_module(f"wordtally.{name}")
def edit(name, old, new):
"""Replace the one place where old appears in the project's file name with new."""
text = read(name)
if text.count(old) != 1:
print(f"{name} doesn't contain that text exactly once, so it wasn't changed.")
return
write(name, text.replace(old, new))
def set_version(new):
"""Change the version line in pyproject.toml to new."""
text, count = re.subn(r'(?m)^version\s*=\s*"[^"]*"', f'version = "{new}"',
read("pyproject.toml"))
if count != 1:
print("pyproject.toml has no version line, so it wasn't changed.")
return
write("pyproject.toml", text)
def run_git(command, folder=PROJECT):
"""Run a Git command in folder, and return its output and exit status."""
arguments = shlex.split(command) if isinstance(command, str) else list(command)
result = subprocess.run(
[GIT, *OPTIONS, *arguments], cwd=folder, env=ENVIRONMENT, timeout=60,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8",
errors="replace",
)
return result.stdout, result.returncode
def git(command):
"""Run a Git command as a terminal would, and show its output, and its status if not 0."""
output, status = run_git(command)
print(output, end="")
if status != 0:
print(f"(exit status {status})")
def git_output(command):
"""Run a Git command, and return what it printed."""
return run_git(command)[0]
remove(PROJECT)
(PROJECT / ".github" / "workflows").mkdir(parents=True)
write(".gitignore", "__pycache__/\n")
write("README.md", "# wordtally\n\nPrint the most common words in a text file.\n")
write("sample.txt", "Rain on the harbor, rain on the hill.\n"
"The gauges fill, and the river is still.\n"
"Rain again tomorrow, the forecast says.\n")
write("src/wordtally/__init__.py", '"""Count the words in text files."""\n')
write("src/wordtally/__main__.py", '''"""Run the wordtally command with python -m wordtally."""
import sys
from wordtally.cli import main
sys.exit(main())
''')
write("src/wordtally/counting.py", '''"""Count the words in a text."""
import re
WORD = re.compile(r"[a-z]+(?:'[a-z]+)*")
def count_words(text: str) -> dict[str, int]:
"""Return how many times each word appears in text, ignoring case."""
counts: dict[str, int] = {}
for word in WORD.findall(text.lower()):
counts[word] = counts.get(word, 0) + 1
return counts
def top_words(counts: dict[str, int], n: int) -> list[tuple[str, int]]:
"""Return the n most common words with their counts, most common first.
Words with the same count keep the order in which they first appeared.
"""
return sorted(counts.items(), key=lambda item: item[1], reverse=True)[:n]
''')
write("src/wordtally/cli.py", '''"""The wordtally command."""
import argparse
import sys
from importlib.metadata import version
from pathlib import Path
from wordtally.counting import count_words, top_words
def main(argv: list[str] | None = None) -> int:
"""Print the most common words in a text file, and return the exit status."""
parser = argparse.ArgumentParser(prog="wordtally", description="Count the words in a file.")
parser.add_argument("--version", action="version", version=f"%(prog)s {version('wordtally')}")
parser.add_argument("file", type=Path, help="a UTF-8 text file")
parser.add_argument("--top", type=int, default=3, help="how many words to print (default 3)")
args = parser.parse_args(argv)
try:
text = args.file.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as error:
print(f"wordtally: can't read {args.file}: {error}", file=sys.stderr)
return 1
for word, count in top_words(count_words(text), args.top):
print(f"{word:<12} {count}")
return 0
''')
write("tests/test_counting.py", '''from wordtally.counting import count_words, top_words
def test_count_words_ignores_case_and_punctuation():
assert count_words("Rain, rain; go away!") == {"rain": 2, "go": 1, "away": 1}
def test_top_words_keeps_the_first_seen_order_for_ties():
assert top_words({"go": 1, "rain": 2, "away": 1}, 2) == [("rain", 2), ("go", 1)]
''')
print("Ready:", PROJECT)1. A package and its command¶
The setup cell wrote every file of the project except pyproject.toml, in the src layout:
wordtally/
├── .gitignore
├── README.md
├── sample.txt
├── src/
│ └── wordtally/
│ ├── __init__.py
│ ├── __main__.py
│ ├── cli.py
│ └── counting.py
└── tests/
└── test_counting.pyRead cli.py in the setup cell. Its main function is the command: it reads the file named on
the command line, and prints its three most common words, or as many as --top says. It finds
its own version with importlib.metadata.version, so the version comes from pyproject.toml.
Exercise L18.1 (LO-18.1, ★★, about 20 minutes)¶
Write the project’s pyproject.toml in the next cell, above the tables that are already
there. It needs:
a
[build-system]table that builds the package with Hatchling 1.26 or newer, as the reading’s does;a
[project]table with the namewordtally, the version0.1.0, the description “Print the most common words in a text file.”, Python 3.12 or newer, and no dependencies;a
[project.scripts]table that makes a command,wordtally, which calls the functionmainin the modulewordtally.cli.
Leave the [tool...] tables at the end as they are: they set up Ruff and mypy for sections 2
and 3. The check reads your file, installs the package, and runs its command.
Hint
The reading’s pyproject.toml for rainkit has the same tables. Leave out readme, license, and license-files, because this project has no LICENSE file.
%%writefile scratch/lab18/wordtally/pyproject.toml
# Write the [build-system], [project], and [project.scripts] tables here, in place of this line.
[tool.ruff]
line-length = 100
[tool.ruff.lint]
select = ["E", "F", "I", "B"]
[tool.mypy]
strict = truefound = settings()
build = found.get("build-system", {})
assert build.get("build-backend") == "hatchling.build", (
"[build-system] needs build-backend = \"hatchling.build\""
)
assert any(re.fullmatch(r"hatchling\s*>=\s*1\.26", item) for item in build.get("requires", [])), (
"[build-system] needs requires = [\"hatchling >= 1.26\"]"
)
project = found.get("project", {})
assert project.get("name") == "wordtally", "[project] needs name = \"wordtally\""
assert project.get("version") == "0.1.0", "[project] needs version = \"0.1.0\", as a string"
assert project.get("description") == "Print the most common words in a text file.", (
"[project] needs the description, exactly as the exercise gives it"
)
assert project.get("requires-python", "").replace(" ", "") == ">=3.12", (
"[project] needs requires-python = \">=3.12\""
)
assert project.get("dependencies") == [], "[project] needs dependencies = [], an empty list"
assert project.get("scripts") == {"wordtally": "wordtally.cli:main"}, (
"[project.scripts] needs wordtally = \"wordtally.cli:main\": the module, a colon, and the "
"function"
)
assert install() == 0, "pip couldn't install the package: read its message above"
assert command("--version", show=False)[0] == "wordtally 0.1.0\n", (
"wordtally --version should print wordtally 0.1.0"
)
output, status = command("sample.txt")
assert status == 0 and re.search(r"(?m)^the +5$", output), "wordtally sample.txt didn't work"
print("passed")The package is installed in your course environment now, beside JupyterLab and pytest. Its
command, wordtally, is in the same folder as the environment’s python:
print(shutil.which("wordtally", path=str(Path(sys.executable).parent)))
command("sample.txt", "--top", "5")
command("missing.txt")python -m wordtally runs the same main through __main__.py, and pytest finds the package
because it is installed:
run("wordtally", "--version")
run("pytest", "-q")Exercise L18.2 (LO-18.1, ★, about 10 minutes)¶
Predict, then run the three cells after the check to see.
p1: the first cell changescli.pyso that it prints a heading above the words. Will thewordtallycommand print the heading without installing the package again? AnswerTrueorFalse.p2: the second cell changes the version inpyproject.tomlto0.1.1, and runswordtally --versionwithout installing again. What does it print? Answer with the line it prints, as a string, without the newline.p3: the third cell installs the package again, and runswordtally --version. What does it print?
p1 = None
p2 = None
p3 = Noneassert p1 is True, "p1: an editable install points at src, so a change to the code shows at once"
assert p2 == "wordtally 0.1.0", (
"p2: the version is one of the package's details, which pip recorded when it installed it"
)
assert p3 == "wordtally 0.1.1", "p3: installing again records the new version"
print("passed")edit("src/wordtally/cli.py", " for word, count in top_words",
' print(f"Top words in {args.file}:")\n for word, count in top_words')
command("sample.txt")set_version("0.1.1")
command("--version")install()
command("--version")2. Ruff¶
The next cell writes a new module, report.py, with three functions about the words in a text.
The cell after it runs Ruff on it, with the settings at the end of your pyproject.toml.
Exercise L18.3 (LO-18.2, ★★, about 20 minutes)¶
Change the code in the next cell until both ruff check and ruff format --check pass on
report.py. Then each function must still do what its docstring says.
Fix every finding.
python -m ruff check --fixcan make the safe fixes, but it changes the file, and rerunning this cell would put the old code back, so make them in the cell.Don’t silence any finding with
# noqa.read_textshould catch only the errors that mean the file can’t be read, and let any other error through, such as theTypeErrorfrom passingNoneas the path.
After each change, run this cell, then the cell under it, which shows Ruff’s report and the formatter’s changes. Read what each finding means before you fix it: one of them is a real bug.
Hint 1
Call longest_words("a bb ccc", 2), then longest_words("dddd e"). The second call should return ["dddd", "e"]. What does seen hold when it starts?
Hint 2
seen doesn’t need to be a parameter at all: count_words returns each word once, as a dictionary key. What does open raise when a file is missing, or when you may not read it?
%%writefile scratch/lab18/wordtally/src/wordtally/report.py
"""Questions about the words in a text."""
import re
import sys
from wordtally.counting import count_words
import os
def longest_words(text: str, limit: int = 5, seen: list[str] = []) -> list[str]:
"""Return up to limit different words from text, longest first."""
for w in sorted(count_words(text), key=len, reverse=True):
if w not in seen:
seen.append(w)
return seen[:limit]
def read_text(path: str) -> str:
"""Return the text of a UTF-8 file, or an empty string if the file can't be read."""
try:
with open(path, encoding="utf-8") as file:
return file.read()
except:
print(f"wordtally: can't read the file", file=sys.stderr)
return ""
def sentence_count(text: str) -> int:
"""Return the number of sentences in text, each ending with ".", "!", or "?"."""
l = re.split(r"[.!?]+", text)
return len([s for s in l if s.strip()])run("ruff", "check", "src/wordtally/report.py")
run("ruff", "format", "--diff", "src/wordtally/report.py")source = read("src/wordtally/report.py")
assert "noqa" not in source, "Fix the findings instead of silencing them with # noqa"
output, status = run("ruff", "check", "--output-format", "concise", "src/wordtally/report.py",
show=False)
assert status == 0, "ruff check still finds:\n" + output
output, status = run("ruff", "format", "--check", "src/wordtally/report.py", show=False)
assert status == 0, "ruff format would still change report.py: run the cell above to see how"
report = load("report")
assert report.longest_words("a bb ccc", 2) == ["ccc", "bb"], "longest_words: longest first"
assert report.longest_words("dddd e") == ["dddd", "e"], (
"longest_words: a second call still returns words from the first: the default list is "
"shared between calls"
)
assert report.longest_words("one two three four five six seven") == [
"three", "seven", "four", "five", "one"
], "longest_words: at most limit words, and words of the same length in the order they appear"
assert report.read_text(str(PROJECT / "missing.txt")) == "", "read_text: \"\" for a missing file"
assert report.read_text(str(PROJECT / "sample.txt")).startswith("Rain on the harbor")
try:
report.read_text(None)
except TypeError:
pass
else:
raise AssertionError("read_text(None) should raise TypeError: catch only OSError")
assert report.sentence_count("One. Two! Three?") == 3, "sentence_count: three sentences"
assert report.sentence_count("") == 0, "sentence_count: no sentences in an empty text"
print("passed")3. mypy¶
The next cell writes stats.py, another new module. Ruff finds nothing in it, but its type
hints don’t match what its functions do. The cell after it runs python -m mypy src, in strict
mode, from the [tool.mypy] table in your pyproject.toml.
Exercise L18.4 (LO-18.2, ★★, about 20 minutes)¶
Change stats.py until mypy reports no errors in it, without # type: ignore, Any, or
cast: make the hints say what the functions do, and the code handle what the hints say.
describe should return the sentence The text has no words. for a text with no words. Fixing
one error can reveal another, so run mypy after each change.
Hint
Dividing two int values with / gives a float. After word = most_common(text), check word is None before you use word as a string.
%%writefile scratch/lab18/wordtally/src/wordtally/stats.py
"""Statistics about the words in a text."""
from wordtally.counting import count_words
def most_common(text: str) -> str:
"""Return the most common word in text, or None if the text has no words."""
counts = count_words(text)
if not counts:
return None
return max(counts, key=lambda word: counts[word])
def mean_length(words: list[str]) -> int:
"""Return the mean length of words, in letters; words must not be empty."""
return sum(len(word) for word in words) / len(words)
def describe(text):
"""Return a sentence about the most common word in text."""
word = most_common(text)
return f"The most common word is {word.upper()}."run("mypy", "src")source = read("src/wordtally/stats.py")
assert "type: ignore" not in source, "Fix the types instead of silencing mypy with # type: ignore"
names = set()
for node in ast.walk(ast.parse(source)):
if isinstance(node, ast.Name):
names.add(node.id)
elif isinstance(node, ast.Attribute):
names.add(node.attr)
for name in ["Any", "cast"]:
assert name not in names, f"Fix the types instead of using {name}"
output, status = run("mypy", "src/wordtally/stats.py", show=False)
assert status == 0, "mypy still finds:\n" + output
output, status = run("ruff", "check", "src/wordtally/stats.py", show=False)
assert status == 0, "Ruff finds something in stats.py now:\n" + output
stats = load("stats")
assert stats.most_common("Rain, rain, go away") == "rain", "most_common: the most common word"
assert stats.most_common("...") is None, "most_common: None for a text with no words"
assert stats.mean_length(["ab", "abcd"]) == 3.0, "mean_length: (2 + 4) / 2 is 3.0"
assert stats.mean_length(["a", "ab"]) == 1.5, "mean_length: (1 + 2) / 2 is 1.5"
assert stats.describe("Rain, rain, go away") == "The most common word is RAIN."
assert stats.describe("") == "The text has no words.", "describe: the sentence for no words"
print("passed")4. Releasing a version¶
Exercise L18.5 (LO-18.3, ★, about 10 minutes)¶
A package is at version 2.3.1. In
next_version, give the version of the next release after each change, if that change were the only one in the release, as a string such as"2.3.2". The last one is a release with two changes.Python sorts strings character by character, so
sorted(["1.10.0", "1.9.0"])puts 1.10.0 first, because"1"comes before"9". Writeversion_key(text), which returns a key that sorts versions such as"1.10.0"in the right order: a tuple of the three numbers, as integers.
next_version = {
"fixes a crash on empty files": None,
"adds a --min-length option": None,
"removes the --top option": None,
"adds a --json option, and fixes a crash on empty files": None,
}
def version_key(text):
"""Return a key that sorts version numbers such as "1.10.0" in order."""
return textassert next_version["fixes a crash on empty files"] == "2.3.2", "a bug fix raises PATCH"
assert next_version["adds a --min-length option"] == "2.4.0", (
"a new feature raises MINOR, and sets PATCH to 0"
)
assert next_version["removes the --top option"] == "3.0.0", (
"removing an option breaks the commands that use it: raise MAJOR, and set the others to 0"
)
assert next_version["adds a --json option, and fixes a crash on empty files"] == "2.4.0", (
"a release with a feature and a fix raises MINOR, the larger of the two"
)
assert version_key("1.10.0") == (1, 10, 0), "version_key(\"1.10.0\") should be (1, 10, 0)"
versions = ["1.10.0", "1.9.0", "2.0.0", "1.9.12", "1.2.10"]
assert sorted(versions, key=version_key) == ["1.2.10", "1.9.0", "1.9.12", "1.10.0", "2.0.0"]
print("passed")Exercise L18.6 (LO-18.3, ★★, about 10 minutes)¶
Suppose wordtally’s first release was 0.1.0, on November 30, 2026, and these five commits were made since then. The next release is 1.0.0, on December 4, 2026.
Add --top, which sets how many words to print
Fix the crash on files that aren't UTF-8
Split the counting code into count_words and top_words
Print each word's count in a column after the words
Add tests for top_wordsAdd the release to the changelog in the next cell, in the format of the reading’s: a heading
with the version and the date, and under it the changes sorted under ### Added, ### Changed,
and ### Fixed, one entry each. Leave out what doesn’t change anything for a user, and leave
## [Unreleased] empty, because every change is in the release now.
%%writefile scratch/lab18/wordtally/CHANGELOG.md
# Changelog
The notable changes to wordtally, newest first. The format follows
[Keep a Changelog 1.1.0](https://keepachangelog.com/en/1.1.0/), and wordtally uses
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [0.1.0] - 2026-11-30
### Added
- The `wordtally` command, which prints the most common words in a text file.text = read("CHANGELOG.md")
versions = re.findall(r"(?m)^## (.*)$", text)
assert versions == ["[Unreleased]", "[1.0.0] - 2026-12-04", "[0.1.0] - 2026-11-30"], (
"The headings for versions should be, in order: ## [Unreleased], "
"## [1.0.0] - 2026-12-04, and ## [0.1.0] - 2026-11-30. Yours are: " + repr(versions)
)
sections = re.split(r"(?m)^## .*$", text)
assert "- " not in sections[1], "Leave ## [Unreleased] empty: every change is in 1.0.0 now"
release = sections[2]
kinds = {}
for kind, body in re.findall(r"(?ms)^### (\w+)\s*$(.*?)(?=^### |\Z)", release):
kinds[kind] = [line for line in body.strip().splitlines() if line.startswith("- ")]
assert sorted(kinds) == ["Added", "Changed", "Fixed"], (
"1.0.0 should have three sections: ### Added, ### Changed, and ### Fixed. Yours: "
+ repr(sorted(kinds))
)
assert all(len(entries) == 1 for entries in kinds.values()), "Give each section one entry"
assert "--top" in kinds["Added"][0], "The new option, --top, goes under Added"
assert "UTF-8" in kinds["Fixed"][0], "The crash on files that aren't UTF-8 goes under Fixed"
assert "column" in kinds["Changed"][0], "The new layout of the output goes under Changed"
for internal in ["count_words", "top_words", "test"]:
assert internal not in release, (
f"Leave out the commit about {internal}: it changes nothing for someone using wordtally"
)
print("passed")Exercise L18.7 (LO-18.3, ★★★, about 20 minutes)¶
Make wordtally’s checks run on GitHub on every push:
In the first cell, write
requirements-dev.txt: pytest, Ruff, and mypy, each pinned with==to the version in your course environment, which the setup cell printed.In the second cell, write the workflow
.github/workflows/checks.yml. It runs on every push, onubuntu-latest, and its steps check out the repository, set up Python 3.12, install the requirements and the package in editable mode, and then runruff check,ruff format --check,mypy src, andpytest, each in a step of its own.
The check reads both files; GitHub would run them, but this lab doesn’t push anything.
Hint
Start from the reading’s checks.yml. Write the Python version in quotation marks, "3.12": YAML reads an unquoted 3.12 as a number, and an unquoted 3.10 as 3.1.
%%writefile scratch/lab18/wordtally/requirements-dev.txt
# Write the requirements here, in place of this line.%%writefile scratch/lab18/wordtally/.github/workflows/checks.yml
# Write the workflow here, in place of this line.pins = {}
for line in read("requirements-dev.txt").splitlines():
if line.strip() and not line.startswith("#"):
assert "==" in line, f"Pin each package with ==, as in name==version: {line!r}"
name, pinned = line.split("==")
pins[name.strip().lower()] = pinned.strip()
assert sorted(pins) == ["mypy", "pytest", "ruff"], "List exactly pytest, ruff, and mypy"
for name, pinned in pins.items():
assert pinned == version(name), f"{name} is {version(name)} in your environment, not {pinned}"
workflow = yaml.safe_load(read(".github/workflows/checks.yml"))
assert isinstance(workflow, dict), "checks.yml should hold a workflow, with name, on, and jobs"
events = workflow.get("on", workflow.get(True)) # PyYAML reads the key `on` as True
assert events == ["push"] or events == "push", "Run the workflow on every push: on: [push]"
jobs = workflow.get("jobs") or {}
assert len(jobs) == 1, "Give the workflow one job"
job = next(iter(jobs.values()))
assert job.get("runs-on") == "ubuntu-latest", "Run the job on ubuntu-latest"
steps = job.get("steps") or []
assert len(steps) == 7, (
"Give the job seven steps: check out, set up Python, install, and one for each of the checks"
)
uses = [step.get("uses", "") for step in steps]
assert uses[0].startswith("actions/checkout@"), "The first step checks out the repository"
assert uses[1].startswith("actions/setup-python@"), "The second step sets up Python"
assert steps[1].get("with", {}).get("python-version") == "3.12", (
"Set up Python 3.12, with the version in quotation marks: \"3.12\""
)
commands = [step.get("run", "").replace("python -m ", "").strip() for step in steps[2:]]
assert "requirements-dev.txt" in commands[0] and re.search(r"-e \.|--editable \.", commands[0]), (
"The third step installs requirements-dev.txt and the package: "
"python -m pip install -r requirements-dev.txt -e ."
)
CHECKS = ["ruff check", "ruff format --check", "mypy src", "pytest"]
assert sorted(commands[1:]) == sorted(CHECKS), (
"After the install, give each check a step of its own: ruff check, ruff format --check, "
"mypy src, and pytest. Yours: " + repr(commands[1:])
)
print("passed")Run the next cell to run the workflow’s four checks here, as GitHub would. They all pass once you have done Exercises L18.3 and L18.4. Read any failure: each one names the file and the line.
for check in [["ruff", "check"], ["ruff", "format", "--check"], ["mypy", "src"], ["pytest", "-q"]]:
print("$ python -m", *check)
run(*check)
print()Exercise L18.8 (LO-18.3, ★★, about 10 minutes)¶
The next cell makes the project a Git repository, with one commit that holds everything so far.
Then release wordtally 1.0.0 in the cell after it, in the reading’s order: set the version to
1.0.0 with set_version, install the package again, commit the change with the message
Release 1.0.0, and add an annotated tag, v1.0.0, with the message wordtally 1.0.0. Use
git(...) for the Git commands, written as you would type them after git in a terminal.
The project has no remote, so there is nothing to push. To start over, run the next cell again.
remove(PROJECT / ".git")
git("init --quiet")
git("add .")
git('commit --quiet -m "wordtally 0.1.1, with its changelog and workflow"')
git("log --oneline")# Release wordtally 1.0.0 here.assert git_output("cat-file -t v1.0.0").strip() == "tag", (
"There is no annotated tag v1.0.0: git tag -a v1.0.0 -m \"wordtally 1.0.0\""
)
assert git_output("rev-parse v1.0.0^{commit}") == git_output("rev-parse HEAD"), (
"The tag should name the release commit, the newest one: tag after you commit"
)
assert git_output("tag -l --format=%(contents:subject) v1.0.0").strip() == "wordtally 1.0.0", (
"The tag's message should be: wordtally 1.0.0"
)
assert git_output("log -1 --format=%s").strip() == "Release 1.0.0", (
"The release commit's message should be: Release 1.0.0"
)
committed = tomllib.loads(git_output("show HEAD:pyproject.toml"))
assert committed["project"]["version"] == "1.0.0", "The release commit should set version 1.0.0"
assert git_output("status --porcelain") == "", "Commit every change before you tag"
assert command("--version", show=False)[0] == "wordtally 1.0.0\n", (
"wordtally --version should print 1.0.0: install the package again after changing the version"
)
git("log --oneline --decorate")
print("passed")Summary¶
A
pyproject.tomlwith three tables made the project a package: pip installed it, and the[project.scripts]table gave it a command.The editable install picked up a change to the code at once, but a new version only after another install, because pip records the package’s details when it installs it.
Ruff found a shared default list that leaked words from one call into the next, a bare
exceptthat would hide every error, and four smaller problems; its formatter settled the layout.mypy found a function that returned
Noneagainst its hint, and then the crash that theNonewould cause indescribe, before anything ran.Semantic versioning said which number to raise, a key of integers sorted versions correctly, and the changelog told users what changed, without the commits that changed nothing for them.
The workflow ran the same four checks as your computer, with the tools pinned, and an annotated tag marked the release commit.