H2.3 Git workflow, linting and refactoring discipline
Chapter 2: Maintainable Python for ML · Used by: w1d6 · Previous: H2.2 Configuration, logging, reproducible runs Status: Reviewed (sources and what was executed are listed in H2.3.9)
H2.3.1 Overview
Research code is usually versioned as a backup: commit when something works, with a message like “updates”. Engineering code is versioned as an argument: each commit is a claim (“this change moves code and alters nothing”, “this change fixes X and here is the test”), small enough to be checked, and the sequence is the record of why the numbers are what they are.
This section covers three things that make that possible:
- enough of Git’s model to predict what a command will do (H2.3.2 to H2.3.5);
- the discipline of changing structure and behaviour separately, with the tools for it: characterization tests, seams, function extraction (H2.3.6);
- automatic linting and formatting, so that review time is spent on behaviour (H2.3.7).
The single idea underneath all of it: a change you cannot attribute is a change you cannot defend. When a metric moves from 0.91 to 0.78 between two versions of an analysis, the question “which change did that?” must have an answer that does not depend on anyone’s memory.
H2.3.2 Git’s model in one page
Three places a file’s content can be
| Place | What it is | Shown by |
|---|---|---|
| Working tree | the files on disk | your editor; git status |
| Index (staging area) | the exact content of the next commit | git diff --staged |
| History | immutable commits; each is a full snapshot plus parent pointer(s) | git log, git show |
git add copies content from the working tree into the index. git commit turns the index into a
commit. Because the index is a separate place, you can stage half of your edits and commit them
while the other half stays in the working tree. That is the mechanism behind small commits; without
it, a commit is “whatever I happened to have changed”.
git diff (no arguments) compares working tree to index: what I have not staged.
git diff --staged compares index to the last commit: what I am about to commit.
Reading the second one before every commit is the cheapest code review available.
Three places a file’s content can be, the commands that move it, and the two diffs that compare neighbours.
Commits are snapshots, addressed by content
A commit stores a snapshot of every tracked file (shared efficiently between commits), its parent commit(s), author, date and message. Its identifier is a hash of all of that. Two consequences:
- Changing anything in a commit, including its message or its parent, produces a different commit with a different hash. “Editing history” always means creating new commits and moving a branch name to point at them.
- A file that was ever committed remains reachable from that commit. Deleting it in a later commit removes it from the newest snapshot only.
A branch is a movable name pointing at a commit. Creating one costs nothing and copies nothing.
How Git decides a file has changed (and a real incident)
To avoid reading every file on every command, Git records filesystem metadata for each index entry when it is staged and compares that first; if the recorded fields match, the file is taken to be unchanged without looking at its content. Git’s own technical note on the index lists the fields compared: file type and executable bit, modification and change timestamps, owner, inode and size.
This usually stays invisible. While building the worked example for w1d6, a script copied successive
versions of a file into a repository with their modification times preserved. Two versions had
the same size and the same timestamp; Git treated the second as unchanged, git add -A staged
nothing for it, and a commit described as changing the expected output did not contain that change.
The tests passed, because they read the working tree. git show --stat on the commit exposed it.
Two lessons generalise. Tools that preserve timestamps (cp -p, rsync -t, archive extraction,
shutil.copy2) can defeat change detection; and a passing test suite says nothing about whether
your commit contains what you think. Read the commit.
H2.3.3 Commit discipline
What goes in one commit
One logical change, such that the project works after it. A practical test: the message is one sentence and does not need the word “and”.
| Good | Why | Bad | Why |
|---|---|---|---|
Extract load_experiment (no behaviour change) |
verifiable by unchanged output | Refactor loading and fix ids |
two claims, neither verifiable |
Fix: experiment ids came from sort position (BEHAVIOUR CHANGE) |
names the cause; reviewer knows numbers move | fix bug |
which, and did numbers move? |
Add test for files without label columns |
a test alone is a fine commit | WIP |
a save point, not a claim |
Message conventions vary by team. What matters is the content: an imperative summary line of about 50 to 70 characters; then, if needed, a blank line and a body that says why (the diff already says what). For ML code add one habit: if a commit changes any reported number, say so in the summary line. Reviewers scan for it.
Why every commit should pass the tests
git bisect finds the commit that introduced a change by binary search over history. With n
commits between a known-good and a known-bad state it needs about
test runs: 7 for 100 commits, 10 for 1,000. It can be fully automatic (git bisect run <command>,
where exit code 0 means good, 1 to 127 except 125 means bad, and 125 means “cannot test this
commit, skip”). The search only works if intermediate commits are testable. A history with broken
intermediate states turns a ten-step search into reading diffs by hand.
Executed on the six-commit worked example of w1d6, asking “where did the fleet mean stop being 3.603?”:
$ git bisect start HEAD <first commit>
Bisecting: 2 revisions left to test after this (roughly 1 step)
$ git bisect run sh -c 'python explore_meters.py | grep -q "fleet mean kwh per reading: 3.603"'
...
Fix fleet mean: it used M2 rows only (BEHAVIOUR CHANGE)
bisect found first bad commit
The same procedure answers “which commit moved the validation metric?” provided the metric is produced by a deterministic command (H2.2: seeds and run directories are what make that true).
Reviewing your own diff
git status # what changed, what is untracked
git add -p # stage hunk by hunk: y / n / s (split) / q
git diff --staged # read the future commit
python -m pytest -q # does the staged state work?
git commit # message: what claim does this commit make?
git add -p is where you find the debugging print, the commented-out block, the hard-coded path
and the unrelated edit that belongs in another commit. To undo staging use `git restore –staged
` with a reason is acceptable; a blanket ignore is not.
- A linter finding is a hypothesis, not a verdict. It knows nothing about your data.
In the w1d6 reference solution, `ruff check` (version 0.16.9) reported three issues on first run (two
of them unnecessary `int()` casts), all auto-fixable, and `ruff format` rewrote four of seven files.
None was a defect.
That is the typical yield on small, freshly written code; the value shows up on large, old code.
---
## H2.3.8 Practical decisions, failure modes, quick reference
### Decisions and tradeoffs
| Decision | Options | Guidance |
|---|---|---|
| Edit the notebook in place, or write the package fresh beside it | in place gives a characterization-tested path; fresh is faster when the notebook is mostly wrong | In place when its numbers are trusted and must be reproduced; fresh, with an explicit discrepancy table, when they are not. Decide after reading it, not before |
| Commit granularity | per function / per logical step / per day | Per logical step. If you cannot describe it in one sentence, split it |
| Squash before merging | keep all commits / squash to one | Keep the structure-versus-behaviour separation. Squash only noise ("typo", "wip") |
| Keep the notebook in the repository | yes / no | Keep the original export as the first commit (it is the thing being replaced), then stop editing it |
| Data in Git | never / small fixtures / data-versioning tool | Tiny synthetic fixtures yes. Real data no: script plus checksums. A data-versioning tool only when datasets change often enough to need it |
| Formatter and linter | none / in editor / enforced in CI | Editor from day one; CI enforcement in Week 6 |
### Common failure modes
| Failure | Symptom | Prevention |
|---|---|---|
| Refactor and fix in one commit | a metric moved and nobody can say why | separate commits; say BEHAVIOUR CHANGE in the message |
| Trusting the notebook's numbers | the package is "wrong" because it disagrees | treat the output as a claim; audit each disagreement |
| Data committed | repository of hundreds of MB; licence exposure | `.gitignore` first; `git status` before `git add -A` |
| `.gitignore` added too late | file still tracked | `git rm --cached` |
| Secret committed | credential in history | rotate first, then rewrite history |
| `git add -A` reflex | debug prints, scratch files, unrelated edits in history | `git add -p`, `git diff --staged` |
| Broken intermediate commits | `git bisect` unusable | run tests before each commit |
| Cross-group operation | plausible but meaningless statistics | per-group computation; two-unit test |
| Identifier from position | results attributed to the wrong recording | identifiers from the data |
| Giant "initial commit" | no history to reason from | commit the starting point untouched, then proceed in steps |
| Tests depend on local data or cwd | pass locally, fail in CI or elsewhere | tests construct their inputs in `tmp_path` |
| Commit does not contain what you think | tests pass, change missing from history | `git show --stat` after committing |
### Quick reference
```bash
# inspect
git status git log --oneline --stat
git diff git diff --staged
git show git show --stat
# stage and commit deliberately
git add -p git restore --staged # unstage
git commit -m "..." git commit --amend # only if unpushed
git reset --soft HEAD~1 # undo last commit, keep changes staged (unpushed only)
# branches
git switch -c git switch main
git merge git branch -d
# ignoring and untracking
git check-ignore -v git rm --cached # stop tracking, keep file
# finding the commit that changed a result
git bisect start git bisect run # exit 0 good, 1-127 bad, 125 skip
git bisect reset
# lint and format (optional)
ruff check . ruff check --fix . ruff format . ruff format --check .
```
**Refactoring loop:** pin output → extract one function (parameters = what it reads, return = what
is used) → run pinned test → commit "no behaviour change" → repeat → then fix one thing with one
test → commit "BEHAVIOUR CHANGE" with the golden diff.
**Before every commit:** Does `git diff --staged` contain only one idea? Do tests pass? Does the
message say whether any number changes?
---
## H2.3.9 Sources and verification status
**Opened in the authoring session (2026-11-21).** The rendered `git-scm.com` and `docs.astral.sh`
sites were not reachable; the same documents were read from their source repositories.
| Claim area | Source read |
|---|---|
| `.gitignore` pattern rules; tracked files unaffected | `git/git` `Documentation/gitignore.adoc` (PATTERN FORMAT, DESCRIPTION) |
| `git add -p` / `--patch` | `git/git` `Documentation/git-add.adoc` |
| `git rm --cached` | `git/git` `Documentation/git-rm.adoc` |
| `git restore --staged`, default source | `git/git` `Documentation/git-restore.adoc` |
| `git switch -c` | `git/git` `Documentation/git-switch.adoc` |
| `git bisect run` exit-code convention | `git/git` `Documentation/git-bisect.adoc` |
| `git filter-repo` recommended over `filter-branch` | `git/git` `Documentation/git-filter-branch.adoc` |
| Stat-based change detection, fields compared | `git/git` `Documentation/technical/racy-git.adoc` |
| `ruff check`, `--fix`, rule-code prefixes, `pyproject.toml` config | `astral-sh/ruff` `docs/linter.md`, `docs/configuration.md` |
| `ruff format` as Black-compatible formatter | `astral-sh/ruff` `docs/formatter.md` |
**Executed:** the `.gitignore` tracked-file transcript in H2.3.5 (scratch repository, Git 2.43.0);
the `git bisect run` transcript in H2.3.3 (on the replayed w1d6 example history); the timestamp
incident in H2.3.2 (occurred while building the example, then reproduced and fixed); `ruff check`
and `ruff format` on the w1d6 reference solution (ruff 0.16.9).
**From memory, not re-verified this session:**
- The terms *characterization test* and *seam* follow Michael Feathers, *Working Effectively with Legacy Code* (2004); *extract function* follows Martin Fowler, *Refactoring* (2nd ed., 2018). Neither book was opened; the procedures here are this handbook's own wording.
- The 50-to-70-character summary-line convention is common practice, not a Git requirement.
- `nbstripout` and `jupytext` are named as examples and were not installed or run.
- `git reset --soft`, `git commit --amend`, merge and rebase behaviour are described from long-standing documented behaviour; their manual pages were not re-read this session.
- The statement that ruff's default rule set has changed between versions is based on the development documentation read this session describing a category-based default selection that differs from earlier documented defaults; the exact defaults of ruff 0.16.9 were not enumerated.