Sub topic 9
Moving Reusable Logic into Modules
This chapter assumes you can write Python functions, use Jupyter, and run a clean "restart and run all" check. It also assumes you have a project layout with a src/ folder, as described in the earlier chapter on layout.
Why logic should leave the notebook
Notebook cells are hard to test, hard to review in Git, and easy to run out of order. Copying a cleaning cell between notebooks produces slightly different versions of the same code, and results drift apart.
A module is a plain .py file whose functions you import. Moving logic into modules gives you three things:
- One definition used by every notebook.
- Functions that take inputs and return outputs, so they carry no hidden state.
- Code you can test without opening Jupyter.
The notebook stays as the place for narrative, parameters, and plots. The module holds the work.
What to move
Move code that you have copied, that you would want to test, or that changes data. Leave exploratory one-off lines in the notebook.
| Keep in the notebook | Move to a module |
|---|---|
| Plot tweaks and quick looks at data | Cleaning and feature functions |
| Text explaining findings | Loading and validation code |
| Parameter values | Statistical routines used more than once |
A worked example
Suppose a notebook cell cleans a measurements file and removes outliers. It reads a global df and a global threshold.
# Notebook cell before refactoring
df = df[df["value"].notna()]
df = df[df["value"] < threshold]This cell works only if df and threshold already exist. Rewrite it as a function in src/cleaning.py. Everything the function needs is an argument, and it does not modify its input.
# src/cleaning.py
import pandas as pd
def clean_measurements(df: pd.DataFrame, threshold: float) -> pd.DataFrame:
"""Drop missing values and values at or above the threshold."""
kept = df[df["value"].notna()]
kept = kept[kept["value"] < threshold]
return kept.reset_index(drop=True)A small test shows the behavior without a notebook:
# tests/test_cleaning.py
import pandas as pd
from cleaning import clean_measurements
def test_clean_measurements_drops_missing_and_large():
df = pd.DataFrame({"value": [1.0, None, 5.0, 100.0]})
result = clean_measurements(df, threshold=10.0)
assert list(result["value"]) == [1.0, 5.0]Run it with python -m pytest. Pytest needs to find src, so either install the project in editable mode with pip install -e . (this needs a pyproject.toml), or set pythonpath = ["src"] under [tool.pytest.ini_options] in pyproject.toml.
Importing in the notebook
Use the notebook's autoreload extension while you edit the module. Without it, Jupyter keeps the old version of the module in memory, which is a form of hidden state.
%load_ext autoreload
%autoreload 2
from cleaning import clean_measurements
clean = clean_measurements(raw, threshold=10.0)If the import fails, check that the notebook's kernel uses the project's virtual environment and that src is importable. Autoreload is a convenience for editing. Always confirm the result with a restart and run all, because autoreload can miss changes to some objects.
Common errors
- Functions that read globals. A function that uses a notebook variable it was not given will fail when imported. Pass every value as an argument.
- Functions that change their input. Modifying a DataFrame in place makes results depend on call order. Return a new object instead.
- Hidden randomness. Do not call
np.random.seedinside a module. Accept anrngargument so the caller controls the seed. - Side effects at import time. Code at the top level of a module, such as reading a file, runs on import. Put it inside functions.
- Moving too much. A module full of functions used once makes the analysis harder to follow. Move code when it is reused or needs tests.
Exercise
A function in your module draws a random sample using np.random.default_rng(42) inside its body. Why does this hurt reproducibility work, and how would you change it?
Show answer
The seed is fixed inside the module, so a caller cannot change it or record it, and every call returns the same draw. Add an rng parameter (or a seed parameter) and have the notebook create the generator from a recorded seed and pass it in. The function then uses rng.choice or rng.normal on the generator it was given.
Exercise
You moved a cleaning function to src/cleaning.py and edited it, but the notebook still shows the old behavior. Name two likely causes and one fix.
Show answer
The kernel still holds the old module in memory because autoreload is not enabled, or the kernel uses a different environment that imports another copy of the module. Enable %autoreload 2 or restart the kernel, and confirm with "restart and run all" that the notebook uses the current file.