Sub topic 10
Parameterizing a notebook
This chapter assumes you can run a notebook end to end, use the command line, and have a pinned environment from the earlier chapters. It also assumes you have run "Restart and run all" as a routine check. Parameterizing builds on that check. A notebook can only be run by a script if it runs cleanly from top to bottom.
Why parameterize
Many notebooks contain values that someone edits by hand before each run: a smoothing factor, an input file, a date range. Hand edits cause three problems:
- The edit is not recorded. Nobody can tell which value produced a saved result.
- The edit is easy to forget or to make halfway, which leaves the notebook in a mixed state.
- Running the analysis for ten values means ten manual sessions.
Parameterizing means you declare which values are inputs, put them in one place, and let a tool supply them from outside. The notebook's code stays the same. Only the inputs change, and each run records the inputs it used.
The parameters cell
The convention used by Papermill, the most common tool for this, is a single code cell near the top. You tag that cell parameters. In JupyterLab, open the property inspector and add the tag. In classic Jupyter, use View, Cell Toolbar, Tags.
# Cell tagged "parameters"
alpha = 0.05
input_path = "data/raw/measurements.csv"
seed = 20240601
n_bootstrap = 1000The values in this cell are defaults. If you run the notebook by hand, the defaults apply. If you run it through Papermill, the tool overrides them.
Keep the cell simple:
- Use only plain assignments of strings, numbers, booleans, lists, and dictionaries.
- Do not compute values here, call functions, or read files.
- Put imports in a separate cell below, so the parameters cell stays easy to read and replace.
How injection works
Papermill does not edit your parameters cell. It reads the notebook, finds the cell with the parameters tag, and inserts a new cell directly after it. That cell is tagged injected-parameters and holds your overrides as ordinary assignments. Because it runs later, its assignments win over the defaults.
The input notebook is never modified. The output notebook is a full copy that holds the injected cell, all outputs, and any error. That makes the output notebook a record of the run.
Running with different values
Install Papermill in your pinned environment:
pip install papermillThen run the notebook with an override:
papermill analysis.ipynb outputs/analysis_alpha_0.1.ipynb -p alpha 0.1Name the output file after the parameter values. A later reader can tell which run it was before opening it.
Setting several values
Repeat -p for each parameter:
papermill analysis.ipynb outputs/analysis_a0.1_s7.ipynb \
-p alpha 0.1 \
-p seed 7 \
-p input_path data/raw/measurements_v2.csvFor longer lists, put the values in a YAML file and pass it with -f:
alpha: 0.1
seed: 7
input_path: data/raw/measurements_v2.csv
n_bootstrap: 5000papermill analysis.ipynb outputs/analysis_run3.ipynb -f params/run3.yamlA committed parameter file gives you an exact, reviewable description of a run. This is a better record than a command typed into a terminal.
Types
Papermill converts command-line values into Python types. 0.1 becomes a float, 7 an integer, and true a boolean. This causes a common surprise with identifiers that look like numbers. A run label of 007 or 1e3 may not stay a string. Use -r (raw) to force a string:
papermill analysis.ipynb outputs/run.ipynb -r run_label 007Check the types inside the notebook. A short validation cell right after the parameters catches mistakes before they cost a long run:
assert 0 < alpha < 1, f"alpha must be between 0 and 1, got {alpha}"
assert isinstance(seed, int), f"seed must be an int, got {type(seed)}"
assert n_bootstrap > 0Running from Python
The same operation is available as a function. This is useful for looping over a grid of values:
import papermill as pm
for alpha in [0.01, 0.05, 0.1]:
pm.execute_notebook(
"analysis.ipynb",
f"outputs/analysis_alpha_{alpha}.ipynb",
parameters={"alpha": alpha, "seed": 20240601},
)If any cell raises an error, Papermill stops and raises PapermillExecutionError. The partially executed output notebook is still saved, with the failing cell marked, so you can open it and see where the run failed.
What to parameterize
Not every constant should be a parameter. Each parameter is part of the notebook's interface, and it increases the number of runs you may need to test.
| Good candidates | Poor candidates |
|---|---|
| Input file path or dataset version | Column names fixed by the data format |
| Random seed | Plot colors and font sizes |
| Model hyperparameters you want to compare | Internal intermediate variables |
| Date range or filter thresholds | Values derived from other parameters |
| Output directory or run label | Library configuration |
A useful test: would two different people reasonably want different values for this? If so, make it a parameter. If the value is a fixed fact of the analysis, leave it in the code.
Gotchas
- No tagged cell. If no cell has the
parameterstag, Papermill still runs the notebook. It injects the new cell at the top and warns that no parameters cell was found. Your defaults do not exist, and any variable you did not pass is undefined. Always check for the tag. - Parameters used before they are set. An import or setup cell above the parameters cell cannot see the injected values. Keep the parameters cell first, after only the title and a comment cell.
- Derived values in the parameters cell. A line like
output_dir = f"outputs/{alpha}"in the tagged cell uses the defaultalpha. The injectedalphaarrives afterward, sooutput_dirkeeps the old value. Compute derived values in a cell after the parameters. - Seeds are parameters too. If the seed is hard-coded in a later cell, passing
-p seed 7does nothing. Search for hard-coded copies of each parameter. - Output paths that collide. Two runs that write
results/summary.csvoverwrite each other. Include the run label or parameter values in every output path. - Shared environment. Parameterized runs only match when the environment matches. Run Papermill inside the pinned virtual environment, and make sure the kernel name in the notebook refers to that environment.
Using parameters in the notebook body
Write the rest of the notebook so that every file path and every random generator comes from the parameters. This example reads the input path and the seed from the parameters, and writes an output whose name includes them:
from pathlib import Path
import numpy as np
import pandas as pd
rng = np.random.default_rng(seed)
df = pd.read_csv(input_path)
boot_means = [
df["value"].sample(frac=1.0, replace=True, random_state=int(rng.integers(2**31))).mean()
for _ in range(n_bootstrap)
]
low, high = np.quantile(boot_means, [alpha / 2, 1 - alpha / 2])
out_dir = Path("outputs")
out_dir.mkdir(exist_ok=True)
pd.DataFrame({"low": [low], "high": [high]}).to_csv(
out_dir / f"interval_alpha_{alpha}_seed_{seed}.csv", index=False
)
print(f"{1 - alpha:.0%} interval: [{low:.3f}, {high:.3f}]")With the same input file and the same parameters, this cell gives the same interval every time.
Parameterization and modules
If the notebook grows many parameters and long logic, the earlier advice on modules applies. Move the computation into a function in src/, such as bootstrap_interval(df, alpha, n_bootstrap, seed). The notebook then holds only the parameters cell, a call to the function, and the plots and tables. The function can be unit tested, and the notebook becomes a thin report that is easy to run with many parameter sets.
Exercise
A colleague runs papermill analysis.ipynb out.ipynb -p alpha 0.1 and finds that the results are identical to the default run with alpha = 0.05. The notebook has a cell tagged parameters that sets alpha = 0.05. A later cell contains the line alpha = 0.05. What went wrong, and how do you fix it?
Show answer
The later cell reassigns alpha after Papermill's injected cell has set it to 0.1, so the override is lost. Remove the hard-coded assignment from the later cell, and use the value from the parameters cell. Also search the notebook for other hard-coded copies of each parameter, and add a validation cell that prints the value in use so the run records it.
Exercise
You pass -p run_label 007 and the notebook builds a path with f"outputs/run_{run_label}". The folder is named run_7. Why, and how do you get run_007?
Show answer
Papermill converts the value 007 to the integer 7. Pass it as a raw string with -r run_label 007, or quote it inside a YAML parameter file as run_label: "007".