Sub topic 11
Keeping notebooks reviewable in Git
This chapter assumes you can commit, branch, and open a pull request in Git. It also assumes you have used Jupyter notebooks and a virtual environment. The goal is to make notebook changes show up in Git as small, readable diffs that a reviewer can check.
Why notebooks are hard to review
A .ipynb file is JSON. It holds your source cells, but it also holds everything else the notebook produced or recorded:
- Cell outputs, including text, tables, and plots.
- Images, stored as base64 text inside the JSON.
- Execution counts, the
[17]numbers beside each cell. - Metadata, such as the kernel name, the Python version, and cell IDs.
A one-line code change can therefore produce a diff with thousands of changed lines. Re-running a notebook with no code change at all can also change the file, because the execution counts and the image bytes differ. Reviewers cannot find the real change in that noise. Merge conflicts also become likely, because two people who both ran the notebook have both rewritten the outputs.
There are two separate problems here:
- Noise. Outputs and metadata change even when the analysis logic does not.
- Size. Embedded images and large tables make the repository heavy and slow to clone.
Most of the techniques below remove the noise by keeping outputs out of the commit. The rest make the remaining diff easy to read.
Strip outputs with nbstripout
nbstripout is a tool that removes outputs and execution counts from a notebook. It installs as a Git filter, so it runs when you stage a file. Your working copy keeps its outputs. Only the committed version is clean.
pip install nbstripout
nbstripout --installRun nbstripout --install once inside each repository. It writes filter settings into the repository's .git/config and adds a rule to .git/info/attributes. That means the filter is a local setting. A teammate who clones the repository does not get it automatically, so each person must run the install command after cloning.
To enforce the habit for everyone, add nbstripout to your project's requirements file and mention the install step in the README. Section "Check it in CI" below shows a way to fail a build when outputs slip through.
Check what the filter does
You can test the filter without committing:
nbstripout --dry-run analysis.ipynbThe --dry-run flag lists the files that would be changed and does not write them. If you want to remove outputs from a file already in the repository, run nbstripout analysis.ipynb and commit the result. That commit will be a large one-time diff. After it, later diffs stay small.
Keep some outputs on purpose
Stripping everything is the safe default, but a notebook that is meant to be read on GitHub looks empty without its figures. You have two options:
- Commit stripped notebooks, and publish executed copies elsewhere, such as an
outputs/folder or a documentation site, produced by a headless run. - Keep outputs in selected notebooks and exclude those from the filter. Use a path-specific rule in
.gitattributesand do not apply the filter to those files.
The first option keeps the history clean and makes every published result come from a known, clean run. The second is simpler but brings the noise back for those files.
Pair a notebook with a plain-text file
Another approach is to store the notebook as a script and treat the .ipynb as a generated artifact. Jupytext converts between a notebook and a text format such as a percent-format Python file. In that format, each cell starts with a # %% comment line.
pip install jupytext
jupytext --set-formats ipynb,py:percent analysis.ipynbThis command pairs the two files. When you save the notebook in Jupyter, both files update. You then commit the .py file, and reviewers read ordinary Python diffs. The .ipynb can be committed too, stripped of outputs, or left out of Git and regenerated.
Here is what a paired file looks like:
# %% [markdown]
# # Measurement summary
# %%
import pandas as pd
df = pd.read_csv("data/raw/measurements.csv")
df.describe()Paired scripts have a few trade-offs:
| Approach | Diff quality | Setup cost | Keeps outputs in Git |
|---|---|---|---|
| Commit raw `.ipynb` | Poor | None | Yes |
| `nbstripout` filter | Good | One command per clone | No |
| Jupytext pairing | Very good | Config file and a paired file | No |
| Both combined | Very good | Highest | No |
Pairing also lets you use normal tools on the code, such as linters, formatters, and search. The cost is two files per notebook, which can fall out of sync if someone edits one outside Jupyter without updating the other. Jupytext can resync them with jupytext --sync analysis.ipynb.
Review notebooks with notebook-aware diffs
Sometimes you do need to compare two notebooks, including their outputs. Plain git diff is a poor tool for that. The nbdime package provides diff and merge tools that understand the structure of a notebook.
pip install nbdime
nbdime config-git --enable
git diff analysis.ipynbAfter config-git --enable, Git uses nbdime for .ipynb files. It shows changes cell by cell and separates source changes from output changes. It also provides a merge driver. When two branches edit the same notebook, nbdime merges at the cell level instead of leaving conflict markers in the middle of JSON.
Notebook-aware diffs help most when outputs are in the commit. With stripped notebooks, a plain diff is already readable, and nbdime mainly helps with merges and with cell reordering.
Habits that keep diffs small
Tools do most of the work, but a few habits matter as well:
- Run Restart and Run All before committing. This is the check from earlier in the tutorial. It means the committed code works from top to bottom. Stripped outputs do not hide a notebook that only works in a particular cell order.
- Make small, focused commits. Change one analysis step per commit, so a reviewer can follow it.
- Move logic into modules. Code in a
.pyfile diffs better than code in a cell and can be tested. Notebooks then hold the narrative and the calls. - Do not commit large data files or generated images. Keep them out with
.gitignore, and record their provenance instead. - Write commit messages that say what changed in the analysis. "Exclude sensor 4 from the baseline" tells a reviewer more than "update notebook".
A starting .gitignore for the project layout used in this tutorial might contain:
.venv/
.ipynb_checkpoints/
data/raw/
outputs/
__pycache__/Adjust it to your project. If you do need to version a raw data file, consider a tool built for large files rather than plain Git, and keep the checksum in the repository either way.
Check it in CI
You can also fail a build when a notebook is committed with outputs. nbstripout has a mode that checks for them without changing files. The exit status is non-zero if any notebook would be modified.
nbstripout --verify analysis.ipynbPut this command in your automated checks so a pull request with outputs gets flagged. That moves the rule from "everyone must remember" to "the build enforces it". The next chapters cover how to run notebooks in automated jobs.
Common mistakes
- Installing the filter in one clone and assuming it is global. It is per repository and per clone. A new clone needs
nbstripout --installagain. - Stripping outputs and losing the only copy of an expensive result. If a notebook takes hours to run, save the result to a file under
outputs/before relying on a clean commit. - Committing only the
.pyfile and forgetting the pairing config. Without the Jupytext settings in the repository, a teammate's Jupyter will not keep the pair in sync. - Reviewing outputs in a pull request that has none. If the reviewer needs to see a figure, attach the executed copy from a headless run or link to a published version.
- Resolving conflicts by hand inside JSON. Use
nbdimemerge, or regenerate the notebook from the paired script.
Exercise
A teammate clones your repository and commits a notebook. The pull request diff shows thousands of changed lines, mostly base64 image data, even though they edited only one line of code. You use nbstripout. What is the most likely cause, and what should the teammate run?
Show answer
The nbstripout filter is stored in each clone's local Git configuration, so it was never installed in the teammate's new clone. The teammate should run nbstripout --install in the repository, then run nbstripout analysis.ipynb on the notebook (or re-stage it) and amend the commit so the outputs are removed. Adding nbstripout --verify to CI will catch this in future.
Exercise
Why might you pair a notebook with a Jupytext percent-format .py file instead of only using nbstripout? Name one benefit and one cost.
Show answer
Benefit: reviewers read an ordinary Python diff, and you can run linters and formatters on the code. Cost: there are two files per notebook, and they can fall out of sync if one is edited without the other, so you need Jupytext settings in the repository and occasionally jupytext --sync.