Sub topic 3
Moving Reusable Code into a Package
Assume you know basic Python modules, functions, imports, and the command line. You should also understand how to run a model from a notebook or script. This chapter focuses on moving stable logic from a notebook into an importable Python package.
Why package the code?
A notebook is useful for exploration. It keeps outputs beside the code and makes it easy to try ideas. It is a poor long-term home for reusable logic, however:
- Cells can run out of order.
- Important values may exist only in notebook state.
- Copying code into a second notebook creates drift.
- Tests and automated jobs cannot easily call individual steps.
A package gives the code a stable import path. A function such as load_training_data() can then be called by a notebook, a training script, a test, or a pipeline stage without copying its implementation.
Use a source package
A common layout places importable code below src/. The package name is separate from the repository name, which prevents accidental imports from the project root.
my_project/
├── pyproject.toml
├── notebooks/
│ └── explore_data.ipynb
├── src/
│ └── my_project/
│ ├── __init__.py
│ ├── data/
│ │ ├── __init__.py
│ │ └── prepare.py
│ └── features.py
└── tests/
└── test_features.pyThe __init__.py files mark directories as Python packages. Keep package modules focused. A data module should prepare data, while a training module should train a model. Avoid putting notebook display code, local file paths, or experiment-specific values inside these modules.
Move logic, not notebook state
Suppose a notebook contains preprocessing code. Extract the transformation into a function with explicit inputs and outputs:
# src/my_project/features.py
import pandas as pd
def add_body_mass_index(frame: pd.DataFrame) -> pd.DataFrame:
"""Return a copy with BMI calculated from height and weight."""
result = frame.copy()
result["bmi"] = result["weight_kg"] / (result["height_m"] ** 2)
return resultThe function does not read a hidden global variable or depend on a previous notebook cell. It accepts a data frame and returns a new data frame. That makes its behavior easier to test and reuse.
A notebook can now contain only exploration and presentation:
from my_project.features import add_body_mass_index
prepared = add_body_mass_index(raw_data)
prepared.head()Install the project in editable mode while developing it:
python -m pip install --editable .Editable installation makes the package importable while still using your working-tree files. The project’s pyproject.toml must declare the package and its dependencies. Run notebooks from the project environment, not from an unrelated system Python installation.
Common errors
- Leaving imports dependent on the current directory: install the package instead of modifying
sys.path. - Mixing configuration with transformations: pass paths and options as arguments or load them in a separate configuration layer.
- Keeping duplicate notebook implementations: delete or replace the old cell after the package version works.
- Using mutable global state: return results explicitly so repeated calls behave predictably.
Exercise
Why is add_body_mass_index easier to test than a notebook cell that reads a global data frame?
Show answer
Its input and output are explicit, so a test can provide a small data frame and compare the returned values without reproducing notebook state.