Sub topic 12
Keep notebooks manageable in Git
This chapter assumes you have a working project virtual environment with JupyterLab installed, and that you know the basic Git workflow: git add, git commit, git diff, and git status. You will set up a repository so that notebooks produce small, readable diffs and so that unwanted files stay out of history.
Why notebooks are awkward in Git
A .ipynb file is a JSON document. Git compares text line by line, so it treats the notebook as one structured blob. A single edit to a cell can change many unrelated lines. These parts of the file cause most of the noise:
- Cell outputs. Tables, tracebacks, and plots are stored inside the file. A plot is a base64-encoded PNG, often hundreds of kilobytes of one unreadable line.
- Execution counts. Each code cell stores a number such as
"execution_count": 17. Re-running a cell changes it, even if the code did not change. - Metadata. Kernel names, Python versions, and cell IDs can differ between machines.
- Embedded data. Printing a large DataFrame stores its text rendering in the file.
The result is that a one-line code fix can produce a diff of thousands of lines. Reviewers cannot find the real change. Merge conflicts also become likely, because two people who run the same notebook will both change outputs.
The usual strategy is to commit the code and Markdown cells and leave the outputs out of the repository. Anyone who needs the results re-runs the notebook or reads an exported report (see the chapter on nbconvert).
Decide what belongs in the repository
Before you configure any tool, decide which files Git should track.
| Item | Commit it? | Reason |
|---|---|---|
| Notebooks (`.ipynb`), with outputs stripped | Yes | They are the source of the analysis. |
| `requirements.txt` | Yes | It lets others recreate the environment. |
| Small reference data (a few MB) | Usually | It keeps the example runnable. |
| Large or private raw data | No | Git history never forgets large files, and private data can leak. |
| `.venv/` | No | It is machine-specific and can be rebuilt from `requirements.txt`. |
| `.ipynb_checkpoints/` | No | Jupyter creates these autosave copies automatically. |
| Exported HTML reports | Case by case | They are generated files, so rebuilding them is often better than storing them. |
Create a .gitignore at the repository root:
.venv/
.ipynb_checkpoints/
__pycache__/
data/raw/
*.csv.gzAdjust the data lines to your project. If a file was already committed, adding it to .gitignore does not remove it. You must run git rm --cached <path> first.
Strip outputs automatically with nbstripout
nbstripout removes outputs and execution counts from a notebook as Git stores it. Your working copy on disk keeps its outputs, so you still see your plots while you work. Only the version that goes into a commit is cleaned.
Run these commands inside the repository, with your virtual environment active:
python -m pip install nbstripout
nbstripout --installThe --install step does two things:
- It adds a filter definition to
.git/config. The filter tells Git which command to run on.ipynbfiles. - It adds a line to
.git/info/attributesthat applies the filter to*.ipynbfiles.
Check that the filter is active:
nbstripout --statusThe diagram shows what happens when you commit.
Share the setup with your team
nbstripout --install changes only your local .git directory. Git does not copy that directory when someone clones the repository. A teammate who clones it gets no filter and can commit outputs by accident.
To keep the attribute rule inside the repository, install it into a tracked file:
nbstripout --install --attributes .gitattributes
git add .gitattributesThe rule line in .gitattributes is committed, but the filter command definition still lives in each person's .git/config. Each collaborator must run nbstripout --install once after cloning. Put that step in your README next to the environment setup.
Check the result
Make a change, then look at the staged diff:
git add analysis.ipynb
git diff --staged --stat analysis.ipynbThe diff should list only your code or Markdown edits. If you see large base64 blocks or "outputs": [...] with content, the filter did not run.
Common errors
- The filter is not found at commit time. The filter calls
nbstripoutby name. If you commit from a terminal where the virtual environment is not active, Git cannot find the command. You may then see errors, or outputs may be committed. Activate the environment before you commit, or use the full path to the executable. - Outputs are already in history.
nbstripoutcleans only new commits. Earlier commits keep their outputs, and rewriting history is a separate, risky operation (see the callout below). - Staged changes still show outputs. The notebook may have been staged before you installed the filter. Run
git rm --cached analysis.ipynb, thengit add analysis.ipynb, to stage it again through the filter. - A diff appears after every checkout. Different tool versions can format JSON differently, for example indentation or key order. Make sure everyone uses the same
nbstripoutversion by listing it inrequirements.txt.
Trade-offs of stripping outputs
Stripping is not free. Consider these costs before you adopt it:
- No results on the hosting site. A site that renders notebooks will show code without plots. If readers need to see results without running anything, publish an exported HTML file instead.
- Slow notebooks cost more. Anyone who wants to see results must re-run the notebook. If one cell takes an hour, save its result to a file in a gitignored directory and load it in the later cells.
- Cleaning can hide real changes. If you intentionally keep an output as part of a tutorial, strip only part of it, or skip the filter for that file.
If outputs matter for a specific notebook, you can tell Git to skip the filter for that path in .gitattributes:
*.ipynb filter=nbstripout
examples/with_outputs.ipynb -filterLater rules override earlier ones, so the specific path must come after the general one.
Review changes with nbdime
Even with clean notebooks, raw JSON diffs are hard to read. nbdime understands notebook structure and compares cell by cell.
python -m pip install nbdime
nbdime config-git --enable
git diff analysis.ipynbAfter config-git --enable, git diff and git merge use nbdime for notebooks. It shows changed cells and ignores unrelated JSON details. You can also run nbdiff old.ipynb new.ipynb directly, or nbdiff-web for a browser view. For merge conflicts, nbdime merges cells as units, which often resolves conflicts that would break the JSON by hand.
An alternative: pair notebooks with plain text
Jupytext stores a notebook as a plain .py file, so Git diffs it like any script. This avoids JSON entirely.
python -m pip install jupytext
jupytext --to py:percent analysis.ipynbThis writes analysis.py. Cells are separated by # %% comment lines. You can open the .py file in JupyterLab as a notebook and commit only the text version.
| Approach | Strength | Weakness |
|---|---|---|
| `nbstripout` | Keeps the `.ipynb` format and needs little setup | Diffs remain JSON for code changes |
| `nbdime` | Readable diffs and cell-aware merges | Reading tool only. It does not clean files |
| `jupytext` | Normal text diffs and easy code review | Two file formats to keep in sync |
Many teams combine nbstripout with nbdime. Jupytext is a better fit when notebooks are mainly code that you review like scripts.
Habits that keep the repository clean
- Restart the kernel and run all cells before you commit. Hidden state then cannot leak into the saved version.
- Commit small, focused changes. Do not mix a refactor with new analysis.
- Move reusable functions into a
.pymodule. Use%autoreloadto import it. Functions in a module diff and test far better than functions in cells. - Name notebooks by purpose, such as
01_clean_sales.ipynb, notUntitled3.ipynb. - Run
git statusbefore each commit to check that no data files or checkpoints are staged.
Exercise
A teammate clones your repository, edits a notebook, and commits it. The commit contains hundreds of lines of base64 image data, although you ran nbstripout --install in your own copy. Give the likely cause and the fix.
Show answer
nbstripout --install writes the filter definition to your local .git/config, which Git does not share through clones. The teammate's clone has no filter, so outputs were committed. The fix is for the teammate to run nbstripout --install once in their clone (with their virtual environment active) and re-stage the notebook with git rm --cached followed by git add. To prevent this in future, commit the attribute rule to .gitattributes and document the install step in the README.
Exercise
You add data/raw/ to .gitignore, but git status still shows changes to files inside it. Why, and what do you run?
Show answer
The files were committed before the ignore rule existed, and .gitignore affects only untracked files. Run git rm -r --cached data/raw/ to stop tracking them while keeping the files on disk, then commit. The files remain in earlier history.