Sub topic 14
Moving Stable Code Out of the Notebook
This chapter assumes you can write pandas functions, import your own Python files, and run cells in Jupyter. You should already have a cleaning function like clean_orders from the earlier chapters.
Why move code out
A notebook is a good place to explore and a poor place to keep logic you depend on. Long cells are hard to test, and copying them between notebooks produces versions that drift apart. Once a step has stopped changing, a module is a better home for it.
Move code when it meets these conditions:
- It has run unchanged for several revisions of the analysis.
- It has clear inputs and outputs, usually a DataFrame in and a DataFrame out.
- You want to reuse it in another notebook or a script.
What moves and what stays
| Stays in the notebook | Moves to a module |
|---|---|
| Plots tuned to one question | Cleaning functions |
| Findings and narrative markdown | Loading helpers with fixed paths and dtypes |
| One-off checks and experiments | Quality reports such as `quality_report` |
The notebook keeps the story and the module keeps the machinery.
A worked example
Create src/orders.py and paste in the cleaning function. Add a docstring and the import it needs, because a module has no hidden notebook state to rely on.
import pandas as pd
def clean_orders(df: pd.DataFrame) -> pd.DataFrame:
"""Return a cleaned copy of the raw orders table.
Drops duplicate rows, normalizes region names, and keeps only
rows with a non-negative amount.
"""
out = df.drop_duplicates().copy()
out["region"] = out["region"].str.strip().str.lower()
out = out[out["amount"].notna() & (out["amount"] >= 0)]
return outIn the notebook, replace the old function cell with an import. The autoreload extension re-imports the module when the file changes, so you can edit it without restarting the kernel.
%load_ext autoreload
%autoreload 2
from src.orders import clean_orders
df = clean_orders(df_raw)
print(f"rows kept: {len(df)} of {len(df_raw)}")Because the function returns a new DataFrame, df_raw stays untouched, as before.
Next, write a small test in tests/test_orders.py and run pytest. A test fixes the rules in place, so a later edit cannot change them silently.
import pandas as pd
from src.orders import clean_orders
def test_clean_orders_drops_duplicates_and_negatives():
df = pd.DataFrame({
"region": [" North", " North", "south"],
"amount": [10.0, 10.0, -5.0],
})
out = clean_orders(df)
assert len(out) == 1
assert out["region"].tolist() == ["north"]Common errors
ModuleNotFoundError: No module named 'src'. Python cannot find your folder. This is common when the notebook lives innotebooks/andsrc/sits one level up. Run Jupyter from the project root, or install the project withpip install -e .. Editingsys.pathalso works, but it is fragile.- Edits that seem to have no effect. Without
autoreload, Python keeps the old import. Enable it, or restart the kernel. - Functions that read notebook globals. A function that uses
df_raworrngwithout receiving it works in the notebook and fails in the module. Pass every dependency as an argument. - Moving code too early. Code that changes every hour belongs in the notebook. Move it once its behavior is settled.
After the move, restart the kernel and run all cells. If the notebook still runs top to bottom, nothing depended on hidden state.
Exercise
A notebook cell defines add_revenue(df), which uses a global variable TAX_RATE to compute a new column. You move the function into src/orders.py, and the notebook now raises a NameError. What is the cause, and how do you fix it?
Show answer
The function relied on TAX_RATE, which was defined in the notebook and does not exist in the module. Pass it as an argument, for example add_revenue(df, tax_rate), or define it as a constant in the module. Then pass the value explicitly from the notebook so the function has no hidden dependencies.