Sub topic 9
Moving reusable logic into modules
This chapter assumes you can write Python functions, use Jupyter notebooks, and run a notebook top to bottom with "Restart and run all". It also assumes you have the project layout from the earlier chapter, with src/, data/, notebooks/, and outputs/ as sibling directories.
Why logic drifts inside notebooks
A notebook cell is easy to edit and easy to copy. Those two properties cause most of the reproducibility trouble that comes from code kept in cells:
- A cleaning step is pasted into three notebooks. One copy gets a bug fix and the other two do not.
- A function is redefined in a later cell with slightly different behavior. Cells that ran before the redefinition used the old version.
- Logic has no tests, because a cell cannot be imported or called from a test runner.
- Diffs in Git mix code changes with output changes, so reviewers cannot see what the logic change was.
A module is a plain .py file. It has one definition for each function, it can be imported from any notebook or script, it can be tested, and it produces clean diffs. The notebook keeps the part it does well: showing the story, the figures, and the interpretation.
What to move and what to keep
Not everything belongs in a module. Use these rules as a starting point.
| Move to a module | Keep in the notebook |
|---|---|
| Loading and cleaning functions | Narrative text and interpretation |
| Feature calculations and statistics | Calls that show a result, such as `df.head()` |
| Plot helpers used by more than one notebook | One-off exploratory plots |
| Constants such as column names and seeds | Parameter values for this particular run |
| Anything you want to test | Short glue code that connects functions |
A good signal is repetition. When you copy a block of cells for the second time, move it into a function. A second signal is size. A cell longer than about 20 lines is usually doing several jobs, and each job can become a function.
Step 1: Create a package directory
Put the module under src/ so that code stays apart from data and outputs. The layout looks like this:
project/
data/
raw/
notebooks/
analysis.ipynb
outputs/
src/
myproject/
__init__.py
cleaning.py
stats.py
tests/
test_cleaning.py
pyproject.tomlThe empty __init__.py marks myproject as a package. The name myproject is a placeholder. Choose a short lowercase name that does not collide with an installed library.
Step 2: Write functions with explicit inputs and outputs
The main rule for a function in a module is that it receives everything it needs as arguments and returns its result. It must not read variables that happen to exist in the notebook. A notebook function that uses a global df works only while that global exists, which is hidden state. A module function cannot see notebook globals at all, so moving code into a module removes that whole class of error.
Here is a module with two small functions:
# src/myproject/cleaning.py
import pandas as pd
def drop_invalid_rows(df: pd.DataFrame, value_column: str) -> pd.DataFrame:
"""Return a copy of df without rows where value_column is missing or negative."""
mask = df[value_column].notna() & (df[value_column] >= 0)
return df.loc[mask].copy()
def add_log_value(df: pd.DataFrame, value_column: str) -> pd.DataFrame:
"""Return a copy of df with a new column log_<value_column>."""
import numpy as np
result = df.copy()
result[f"log_{value_column}"] = np.log1p(result[value_column])
return resultBoth functions return a new DataFrame and leave the input unchanged. This matters for notebooks. If a function modified its argument in place, running a cell twice would apply the change twice, and the result would depend on how many times you clicked.
Randomness follows the same rule. Pass the generator in rather than creating it inside the function:
# src/myproject/stats.py
import numpy as np
def bootstrap_mean(values, n_resamples: int, rng: np.random.Generator) -> np.ndarray:
"""Return n_resamples bootstrap means of values, drawn with the given generator."""
values = np.asarray(values)
indices = rng.integers(0, len(values), size=(n_resamples, len(values)))
return values[indices].mean(axis=1)The caller creates rng once, with a recorded seed, and decides how it is shared. The function stays deterministic given its inputs.
Step 3: Make the package importable
If you run from myproject.cleaning import drop_invalid_rows from a notebook, Python must be able to find myproject. There are three common ways to arrange that, and they differ in how reliable they are.
| Approach | How | Problem |
|---|---|---|
| Edit `sys.path` in the notebook | `sys.path.append("../src")` | Depends on the working directory. Breaks when the notebook is run from elsewhere. |
| Set `PYTHONPATH` | `export PYTHONPATH=src` | Easy to forget. Not recorded in the project. |
| Editable install | `pip install -e .` | Needs a `pyproject.toml`, but works from any directory. |
Prefer the editable install. It links the package into the active virtual environment, so edits to the source take effect without reinstalling. A minimal pyproject.toml is enough:
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "myproject"
version = "0.1.0"
requires-python = ">=3.10"
dependencies = ["numpy", "pandas"]
[tool.setuptools.packages.find]
where = ["src"]Then run this once inside the activated environment:
pip install -e .The dependencies list is a loose declaration of what the package needs. It does not replace the pinned requirements.txt from the earlier chapter. The pinned file records the exact versions that produced your results.
Step 4: Use the module from the notebook
The notebook now imports the functions and calls them. A first cell reloads modules automatically while you are developing:
%load_ext autoreload
%autoreload 2Then the analysis cells become short:
import numpy as np
import pandas as pd
from myproject.cleaning import add_log_value, drop_invalid_rows
from myproject.stats import bootstrap_mean
SEED = 20240601
rng = np.random.default_rng(SEED)
raw = pd.read_csv("../data/raw/measurements.csv")
clean = add_log_value(drop_invalid_rows(raw, "value"), "value")
means = bootstrap_mean(clean["value"], n_resamples=1000, rng=rng)
print(means.mean())The notebook now reads as a sequence of named steps. Anyone reviewing it can follow the analysis without reading the implementation, and can open the module when they need the detail.
The autoreload trap
%autoreload 2 is convenient but is itself a source of hidden state. It patches function objects in the running kernel. Instances created before the reload keep their old class definitions, and some changes, such as renaming a module or changing a dataclass layout, are not picked up reliably.
Use it while you edit a module, then do not trust the results from that session. Before you record a result, restart the kernel and run all cells. With autoreload disabled in the final run, the notebook imports the module exactly as it is on disk.
Test the extracted code
Once the logic is in a module, a test is a few lines. Tests protect you when a later refactor changes behavior without anyone noticing.
# tests/test_cleaning.py
import pandas as pd
from myproject.cleaning import drop_invalid_rows
def test_drop_invalid_rows_removes_missing_and_negative():
df = pd.DataFrame({"value": [1.0, None, -2.0, 3.0]})
result = drop_invalid_rows(df, "value")
assert result["value"].tolist() == [1.0, 3.0]
def test_drop_invalid_rows_does_not_modify_input():
df = pd.DataFrame({"value": [1.0, -1.0]})
drop_invalid_rows(df, "value")
assert len(df) == 2Run them with pytest from the project root. The second test checks the no-mutation rule described earlier.
A safe refactoring sequence
Extract in small steps and check the output after each one. A large rewrite makes it hard to tell which change altered a number.
- Restart the kernel, run all cells, and save the key results, for example a summary table, as the baseline.
- Pick one block of cells. Rewrite it as a function that takes its inputs as arguments.
- Move the function to the module and import it in the notebook.
- Restart and run all again. Compare the results with the baseline.
- Commit the change, then go to the next block.
If the numbers differ at step 4, the cause is in the block you just moved. That is the benefit of a small step.
Common errors
ModuleNotFoundErrorin the notebook. The package is not installed in the kernel's environment. Check that the kernel uses the same virtual environment where you ranpip install -e .. Runimport sys; print(sys.executable)in a cell to see which interpreter the kernel uses.- Old behavior after an edit. The module was imported before the change and autoreload is off. Restart the kernel.
- Circular imports. Two modules import each other. Move the shared code into a third module that both import.
- Hard-coded paths in the module. A path like
"../data/raw/x.csv"inside a module depends on the caller's working directory. Pass paths in as arguments, or compute them from a project root passed by the caller. - Module creates its own seed. Calling
np.random.default_rng(42)inside a function gives every call the same stream. Two calls then return identical "random" values. Accept a generator as an argument instead. - Parameters buried in the module. If an analysis choice, such as a threshold, is a constant in the module, changing it means editing code. Pass it as an argument so the notebook can show and vary it. The next chapter builds on this when it parameterizes a notebook.
Exercise
A notebook cell defines def scale(x): return x / df["value"].max(), using the global df. Rewrite the function so it can be moved into a module, and explain why the original version is a reproducibility risk.
Show answer
Rewrite it as def scale(x, maximum): return x / maximum and call it as scale(x, df["value"].max()). The original reads df from the notebook's global state, so its result depends on whichever DataFrame df currently holds. If df is reassigned, filtered, or not yet defined, the result changes or the call fails, and the outcome depends on cell execution order. A module function cannot see notebook globals, so passing maximum explicitly makes the dependency visible and the function testable.
Exercise
You move a bootstrap function into a module, and it calls np.random.default_rng(42) internally. Two notebook cells call it for two different datasets. What is wrong with this design, and how do you fix it?
Show answer
Every call creates a new generator with seed 42, so every call starts from the same random stream. Results from different datasets share the same random draws, which can hide variability and create correlated outputs. Fix it by adding an rng parameter. The notebook creates one generator from a recorded seed with np.random.default_rng(SEED) and passes it to each call, so draws are repeatable and distinct.
Exercise
After you edit a function in src/myproject/cleaning.py while %autoreload 2 is active, your notebook gives the expected number. What should you do before committing the result, and why?
Show answer
Restart the kernel and run all cells with autoreload off. Autoreload patches objects in a live kernel and can leave stale state, so the number may not match what a fresh run produces. A clean run confirms that the notebook imports the module as it exists on disk.