Sub topic 4
Where notebooks fit
Notebooks are good for looking at data and trying ideas. They are poor at being the place where your project's logic lives. This chapter shows how to keep what notebooks do well and move the rest into the package described in the previous chapter.
This chapter assumes you can write Python functions and modules, use Jupyter or a similar notebook tool, and have a repository with src/, configs/, data/, and tests/ folders as in the layout chapter.
What notebooks are good at, and where they fail
A notebook is a document that mixes code, output, and notes. It runs cells in whatever order you click them, and it keeps variables alive between cells.
That design suits exploration:
- You can look at a plot right after writing the code for it.
- You can keep notes next to results.
- You can share an analysis with someone who does not run your code.
The same design causes problems once a notebook becomes part of a project:
- Hidden state. A cell may work only because of a variable you deleted two hours ago. Another person, or you tomorrow, cannot rerun the notebook from the top and get the same result.
- Order dependence. Running cell 7 before cell 5 gives different results than running them in order, and nothing records which order you used.
- Noisy Git history. A
.ipynbfile is JSON that includes outputs, images, and execution counts. A one-line change produces a diff of hundreds of lines. - Copied code. Each new experiment copies the previous notebook. Within weeks, five notebooks hold five slightly different versions of the same cleaning step.
- No tests. You cannot easily import a function from a notebook into a test file.
These failures work against reproducibility. If a result came from a notebook, you may not be able to recreate it.
The rule: notebooks import, packages define
A simple rule avoids most of these problems. Notebooks call code from src/my_project/. They do not define reusable logic.
Information flows from the package into the notebook. It does not flow back the other way. A script or a pipeline stage can run the same package code without opening a notebook. This also means the logic that produced a result is in a file Git can diff and a test can check.
The table shows how common tasks divide.
| Task | Where it belongs |
|---|---|
| Plotting a distribution to understand a column | Notebook |
| A cleaning function used in more than one place | `src/my_project/` |
| Trying three feature ideas quickly | Notebook, then move the one you keep |
| Writing `data/processed/` or `models/` files | Pipeline stage, not a notebook |
| Hyperparameters and file paths | `configs/train.yaml` |
| Final comparison charts for a report | Notebook that reads saved results |
Making the package importable
For import my_project to work from notebooks/, the package must be installed into the notebook's environment. An editable install links to your source folder, so edits to src/ take effect without reinstalling. Add a minimal pyproject.toml at the repository root:
[project]
name = "my_project"
version = "0.1.0"
requires-python = ">=3.9"
dependencies = ["pandas", "pyyaml"]
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[tool.setuptools.packages.find]
where = ["src"]Then install it from the repository root, in the same environment your notebook kernel uses:
pip install -e .A notebook that starts like this reads its settings from the same config file as the training script:
%load_ext autoreload
%autoreload 2
from pathlib import Path
import pandas as pd
from my_project.config import load_config
from my_project.data.features import clip_outliers
ROOT = Path.cwd().parent # the notebook runs from notebooks/
cfg = load_config(ROOT / "configs" / "train.yaml")
df = pd.read_csv(ROOT / cfg.data_path)
df["income_clipped"] = clip_outliers(df["income"])
df["income_clipped"].describe()This example assumes your data has an income column. Two details are worth noting:
%autoreload 2reloads imported modules before each cell runs. Without it, you would have to restart the kernel after every edit tosrc/.- The data path comes from the config. The notebook does not carry its own copy of
data/processed/train.csv, so changing the config changes the notebook too.
Graduating code out of a notebook
Code starts in a notebook and moves out once it proves useful. Move a piece of code into the package when any of these is true:
- You paste it into a second notebook or script.
- The cell is longer than about ten to fifteen lines.
- The training or prediction path needs the same step.
- A mistake in it would change results without raising an error.
Suppose an exploration cell clips extreme values at the 1st and 99th percentiles. Move that logic into src/my_project/data/features.py:
import pandas as pd
def clip_outliers(
series: pd.Series, lower: float = 0.01, upper: float = 0.99
) -> pd.Series:
"""Clip values to the given quantile range."""
low, high = series.quantile([lower, upper])
return series.clip(lower=low, upper=high)Because it is now a function in a module, you can test it:
import pandas as pd
from my_project.data.features import clip_outliers
def test_clip_outliers_limits_extremes():
s = pd.Series(list(range(100)) + [10_000])
out = clip_outliers(s)
assert out.max() < 10_000
assert out.min() >= s.quantile(0.01)Place this test in tests/. If src/my_project/data/ has no __init__.py, add an empty one so the import works under every tool.
The notebook then calls clip_outliers instead of defining it. When you improve the function, every notebook and every pipeline stage gets the improvement.
Keeping notebooks clean in Git
Even notebooks that only import code are JSON files full of outputs. Three habits keep them manageable.
Strip outputs before committing. The nbstripout tool removes outputs and execution counts through a Git filter:
pip install nbstripout
nbstripout --installRun the second command once inside the repository. Afterward, committed notebooks contain only code and text, so diffs show real changes.
Pair notebooks with plain text, if you want readable diffs. Jupytext keeps a .py file in sync with the .ipynb:
pip install jupytext
jupytext --set-formats ipynb,py:percent notebooks/01-explore.ipynbCommit the .py version if you want reviewers to read changes as ordinary code.
Name notebooks so their order and purpose are clear. A pattern such as 01-explore-income.ipynb and 02-error-analysis.ipynb shows which came first. Add your initials or a date if several people share the folder.
Common mistakes
- Writing results from a notebook. If a notebook saves
data/processed/train.csvormodels/model.pkl, a pipeline cannot reproduce that file, because the pipeline does not know the notebook ran. Generate those files from a stage that declares its inputs and outputs. Notebooks should read them. - Hard-coded paths. A path such as
C:/Users/me/data.csvbreaks on every other machine. Build paths from the config and the repository root, as above. - Treating a notebook as the only record. A result in a notebook is worth little if you cannot say which code version, config, and data produced it. Later chapters on pipelines and experiment tracking address this. For now, keep notebooks small enough that rerunning them is cheap.
- Keeping dead notebooks. An abandoned notebook that no longer runs misleads the next reader. Delete it or move it to an
archive/folder.
Summary of practice
Use notebooks for questions you are still forming. Once an answer becomes a repeated step, write it as a tested function in the package. Keep notebooks import-only for logic, config-driven for settings, and read-only for data and models.
Exercise
A teammate's notebook defines a 40-line function build_features(df) in one cell, and the same cell is copied into two other notebooks. The notebook then saves data/processed/features.csv. Name two changes you would make and where each piece of code should end up.
Show answer
First, move build_features into the package (for example src/my_project/data/features.py), delete the copies from the notebooks, and import it with from my_project.data.features import build_features. Add a test for it in tests/. Second, remove the line that saves data/processed/features.csv from the notebook and put that step in a pipeline stage (for example a script run as python -m my_project.data.prepare) that declares its inputs and outputs. The notebooks then only read the file. Optionally, take the file path from the config instead of hard-coding it.
Exercise
A notebook runs fine on your laptop, but a colleague gets ModuleNotFoundError: No module named 'my_project' after cloning the repository. What are the likely cause and the fix?
Show answer
The package is not installed in the environment the colleague's notebook kernel uses. They should activate that environment (or select its kernel), run pip install -e . from the repository root, and confirm with import sys; print(sys.executable) that the kernel is using the same interpreter.