Sub topic 14
Moving stable code out of the notebook
A notebook is good for exploring and explaining. It is a poor home for functions that you reuse, test, and depend on. This chapter shows when to move code into a module, how to do it without breaking the notebook, and which errors to expect.
This chapter assumes you can write Python functions and imports, run a virtual environment with pip, and have a notebook with a setup cell, a loading step, and a cleaning function like clean_orders from the earlier chapters.
Why move code at all
Cleaning and loading code tends to grow. Once it fills several cells, three problems appear:
- Reuse. A second notebook, a report script, or a scheduled job needs the same cleaning rules. Copying cells creates two versions that drift apart.
- Testing. Cells cannot be tested easily. Functions in a module can be checked with
pytestin seconds. - Readability. The notebook should tell the story of the investigation. Forty lines of string handling bury it.
Moving code does not make the analysis better. It makes the same analysis easier to trust and repeat.
Decide what to move
Move code that is stable, reusable, and independent of the story. Leave code that is still changing or that exists only to support one observation.
| Keep in the notebook | Move to a module |
|---|---|
| One-off plots made to check a hunch | Plot helpers used in several notebooks |
| Findings, hypotheses, and open questions | Loading and parsing functions |
| Experimental cleaning rules you may drop | Cleaning rules you have accepted |
| Cells whose output is the point | Functions with clear inputs and outputs |
A good signal is that you have stopped editing the code. If you changed a rule yesterday, wait.
A project layout that works
Keep notebooks and importable code in separate folders, and put the code in a package under src/.
orders-analysis/
├── pyproject.toml
├── data/
│ └── raw/orders.csv
├── notebooks/
│ └── 01_orders_eda.ipynb
├── src/
│ └── orders_eda/
│ ├── __init__.py
│ ├── cleaning.py
│ └── plots.py
└── tests/
└── test_cleaning.pyA pyproject.toml lets you install the package in editable mode, so the notebook can import it from any folder.
[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"
[project]
name = "orders-eda"
version = "0.1.0"
dependencies = ["pandas", "numpy", "matplotlib"]
[tool.setuptools.packages.find]
where = ["src"]From the project root, with your environment active, run pip install -e .. Editable mode means the installed package points at your source files, so edits take effect without reinstalling. Create an empty src/orders_eda/__init__.py so the folder is a package.
Write the module
Take the cleaning function from the notebook and give it a home. Two rules make functions safe to move: they receive everything they need as arguments, and they return a new object instead of changing the input.
# src/orders_eda/cleaning.py
from pathlib import Path
import pandas as pd
def load_orders(path):
"""Read the raw orders file. The caller decides where it lives."""
return pd.read_csv(Path(path), parse_dates=["order_date"])
def clean_orders(df):
"""Return a cleaned copy of the orders table. The input is not changed."""
out = df.drop_duplicates().copy()
out["region"] = out["region"].str.strip().str.lower()
out = out[out["amount"].notna() & (out["amount"] >= 0)]
return outNotice what is absent. There is no hardcoded data/raw/orders.csv, because a path that works from the notebook folder fails from a script run elsewhere. There is no module-level random generator either. If a function needs randomness, accept a seed or an rng argument so the setup cell stays the single place where the seed is set.
Plot helpers follow the same pattern. Return the figure and let the caller show it.
# src/orders_eda/plots.py
import matplotlib.pyplot as plt
def amount_overview(df):
"""Histogram of amounts plus a box plot by region. Returns the figure."""
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
df["amount"].plot.hist(bins=30, ax=axes[0])
axes[0].set_title("Order amount distribution")
axes[0].set_xlabel("Amount")
axes[0].set_ylabel("Number of orders")
df.boxplot(column="amount", by="region", ax=axes[1])
axes[1].set_title("Order amount by region")
axes[1].set_xlabel("Region")
axes[1].set_ylabel("Amount")
fig.suptitle("")
fig.tight_layout()
return figReturning the figure lets a test or a report script save it with fig.savefig(...). Calling plt.show() inside the helper would block scripts and hide the figure from callers.
Import it in the notebook
Replace the cells that defined the functions with an import. During the move, enable autoreload, an IPython extension that re-imports modules when their files change.
%load_ext autoreload
%autoreload 2
from orders_eda.cleaning import clean_orders, load_orders
from orders_eda.plots import amount_overview
df_raw = load_orders(RAW_PATH)
df = clean_orders(df_raw)
print(f"rows kept: {len(df)} of {len(df_raw)}")
fig = amount_overview(df)RAW_PATH still comes from the setup cell. The notebook now shows the steps and their results, and the rules live in one file.
Confirm the move changed nothing
Before you delete the old notebook function, keep it for one run under a different name, such as clean_orders_nb, and compare both outputs.
pd.testing.assert_frame_equal(clean_orders_nb(df_raw), clean_orders(df_raw))If the assertion passes, the module reproduces the notebook's result and the old cell can go. If it fails, the error message names the column and rows that differ.
Add a small test
A test locks in the rules you decided on. Keep the input tiny so the expected result is obvious.
# tests/test_cleaning.py
import pandas as pd
from orders_eda.cleaning import clean_orders
def test_clean_orders_drops_duplicates_and_bad_amounts():
raw = pd.DataFrame({
"region": [" North", " North", "south", "south"],
"amount": [10.0, 10.0, -5.0, None],
})
out = clean_orders(raw)
assert len(out) == 1
assert out["region"].tolist() == ["north"]
def test_clean_orders_does_not_change_input():
raw = pd.DataFrame({"region": [" North"], "amount": [10.0]})
before = raw.copy()
clean_orders(raw)
pd.testing.assert_frame_equal(raw, before)Run pytest from the project root. The second test guards the rule that raw data stays untouched.
Common errors
Changes to the module do not appear
Python caches imported modules. If you edit cleaning.py and rerun an import cell, you get the old code. Use %autoreload 2, or restart the kernel. Autoreload has limits: objects created before the reload keep their old class definitions, so restart when behavior looks inconsistent.
`ModuleNotFoundError: No module named 'orders_eda'`
The notebook kernel is not using the environment where you ran pip install -e .. Check with import sys; print(sys.executable) in a cell, and select the matching kernel. Avoid fixing this with sys.path.append(...). It works on your machine and breaks on every other one.
A local file shadows a package
Python searches the current folder first. A file named pandas.py or cleaning.py next to the notebook can replace the module you meant to import. Name your own modules distinctly and delete stray copies.
Hidden state leaks into functions
A function that reads a global such as df or SEED from the notebook fails when imported, because the module cannot see notebook variables. Pass every value in as an argument.
Moving too early
If you move rules that are still changing, every experiment becomes an edit, reload, and test cycle. Keep exploratory code in the notebook until you stop editing it.
After the move
Finish with the check from the previous chapter. Restart the kernel, run all cells in order, and confirm that the row counts and plots match what you saw before. Then run pytest. Both should pass from a clean state.
Exercise
You move clean_orders into src/orders_eda/cleaning.py, install the package with pip install -e ., and import it in your notebook. You then change the minimum accepted amount in the module, but the notebook output stays the same after rerunning the import and cleaning cells. Name two possible causes and one fix for each.
Show answer
First, Python cached the already-imported module, so the import cell reuses the old code. Fix this by running %load_ext autoreload and %autoreload 2, or by restarting the kernel. Second, the kernel may be using a different environment from the one where the package was installed, or a stray copy of the file may shadow it. Check sys.executable and orders_eda.cleaning.__file__ to see which file is loaded, then select the right kernel or remove the stray copy.
Exercise
A colleague's helper function plot_amounts(df) calls plt.show() at the end and reads a global variable SEED. List two changes that make it safe to move into a module.
Show answer
Return the figure instead of calling plt.show(), so scripts and tests can save or inspect it. Pass SEED in as an argument, or remove the dependency if the function does not need randomness, so the function relies only on its inputs.