Sub topic 3
Moving reusable code into a package
This chapter assumes you can write Python modules and functions, use Git, and have a repository laid out as in the previous chapter, with importable code under src/. Here you will turn logic that lives in notebooks or loose scripts into an installed package. You will also see the errors that usually appear along the way.
Why a package and not copied files
Most projects start with a notebook. A cell cleans the data, another builds features, a third trains the model. When you need the same cleaning in a second notebook, the quickest fix is to copy the cell. Soon there are three slightly different versions of the cleaning code, and nobody knows which one produced last month's model.
A package fixes this by giving each piece of logic one home, with one import path. A package is a directory of Python modules that you install into your environment, so import my_project works from any directory. Once the code is importable, four things become possible:
- Notebooks, training scripts, and tests all call the same function.
- Tests can import the code without path tricks.
- A change to a function is a single Git diff, not an edit in several places.
- Other people can install the project and run it.
The src layout
Put the package under src/, not at the repository root:
my_project/
├── pyproject.toml
├── src/
│ └── my_project/
│ ├── __init__.py
│ └── data/
│ ├── __init__.py
│ └── prepare.py
└── tests/
└── test_prepare.pyThe src/ folder matters because of how Python finds modules. If my_project/ sits at the repository root, then running pytest or python from the root puts the current directory on the import path. Your tests then import the code in the working tree, whether or not the package is installed correctly. The install can be broken and everything still passes. With src/, the package is importable only after you install it, so a broken install fails on your machine instead of on a colleague's.
Each directory that holds importable code needs an __init__.py. The file can be empty. It marks the directory as a package, and it is where you can later expose a few public names.
Declaring the package in pyproject.toml
pyproject.toml tells the installer the project's name, its dependencies, and where the code is:
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "my_project"
version = "0.1.0"
requires-python = ">=3.10"
dependencies = [
"numpy",
"pandas",
"pyyaml",
]
[tool.setuptools.packages.find]
where = ["src"]The where = ["src"] line is what points the build at the src/ folder. The dependencies list holds what the package needs to run. Exact version pinning for reproducible runs is a separate concern, covered in the environments chapter.
Install the package in editable mode, from the repository root, inside your virtual environment:
python -m venv .venv
source .venv/bin/activate
python -m pip install -e .Editable mode (-e) does not copy the files into the environment. It links the environment to src/, so edits take effect right away without reinstalling. You reinstall only when you change pyproject.toml, for example to add a dependency or a new entry point.
Extracting code from a notebook
Suppose a notebook cell looks like this:
df = pd.read_csv("../data/raw/train.csv")
df = df.dropna(subset=["target"])
df["age"] = df["age"].fillna(df["age"].median())
X = df.drop(columns=["target"])
y = df["target"]This code has a hidden dependency on the notebook's working directory (../data), and it runs only as a top-to-bottom cell. To extract it, apply three rules:
- Turn the logic into functions that take inputs and return outputs.
- Pass paths and options in as arguments. Do not write them inside the function.
- Keep import-time code free of side effects. Importing a module should define things, not read files or train models.
The result in src/my_project/data/prepare.py:
import argparse
import pandas as pd
def clean(df: pd.DataFrame) -> pd.DataFrame:
"""Drop rows without a target and fill missing ages with the median."""
out = df.dropna(subset=["target"]).copy()
out["age"] = out["age"].fillna(out["age"].median())
return out
def split_xy(df: pd.DataFrame, target: str = "target"):
"""Return the feature table and the target column."""
return df.drop(columns=[target]), df[target]
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--input", required=True)
parser.add_argument("--output", required=True)
args = parser.parse_args()
clean(pd.read_csv(args.input)).to_csv(args.output, index=False)
if __name__ == "__main__":
main()The .copy() call avoids modifying a slice of the caller's data. The if __name__ == "__main__": guard lets the same file serve as a library, where from my_project.data.prepare import clean runs nothing, and as a script:
python -m my_project.data.prepare --input data/raw/train.csv --output data/processed/train.csvUse python -m package.module and not python src/my_project/data/prepare.py. Running by path changes how Python resolves imports and breaks imports between modules of your own package.
The paths still come from the command line here. The next chapters move them into a config file.
Using the package from a notebook
The notebook now imports the code and keeps only exploration and plots:
import pandas as pd
from my_project.data.prepare import clean, split_xy
df = clean(pd.read_csv("../data/raw/train.csv"))
X, y = split_xy(df)
X.describe()By default, a running notebook kernel imports a module once and keeps it in memory. If you edit prepare.py, the kernel still uses the old version. Put these two lines at the top of the first cell to reload edited modules automatically:
%load_ext autoreload
%autoreload 2Testing the extracted code
Because the package is installed, a test is a plain import. Save this as tests/test_prepare.py:
import pandas as pd
from my_project.data.prepare import clean
def test_clean_drops_missing_targets_and_fills_age():
df = pd.DataFrame(
{"age": [20.0, None, 40.0], "target": [1, 0, None]}
)
out = clean(df)
assert len(out) == 2
assert out["age"].isna().sum() == 0Run it with python -m pytest. This works from any directory, with no sys.path edits.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `ModuleNotFoundError: No module named 'my_project'` | The package is not installed in the active environment, or the wrong environment is active | Activate the right environment and run `python -m pip install -e .` |
| The notebook shows old behaviour after an edit | The kernel cached the module | Use `%autoreload 2` or restart the kernel |
| `ModuleNotFoundError` for a submodule only | A directory has no `__init__.py`, or it is outside `src/` | Add `__init__.py` and check `where = ["src"]` |
| `ImportError: cannot import name` with a circular-import message | Two modules import each other | Move the shared code into a third module that both import |
| Importing a module starts a training run | Top-level code outside functions | Move it into a function and add the `__main__` guard |
| Your module shadows a library, for example `random.py` | The file name matches a standard library or installed package | Rename it, for example to `sampling.py` |
What belongs in the package
Not everything should move. A reasonable rule is that code moves into the package once a second caller needs it, or once it needs a test. Typical residents are data cleaning, feature construction, model definition, training and evaluation loops, and metric functions. Exploratory plots, one-off checks, and scratch analysis stay in notebooks, which the next chapter covers.
Keep the package's own structure shallow. Group modules by what they do (data/, features/, models/) and avoid a utils.py that collects unrelated helpers, since such a file grows without limit and hides where things live.
Exercise
After running python -m pip install -e ., your teammate's pytest run fails with ModuleNotFoundError: No module named 'my_project', but yours passes. Give two likely causes that follow from this chapter, and one way to check each.
Show answer
First, the package is not installed in the environment your teammate is using, for example because they have not run python -m pip install -e . or have a different environment active. Check with python -m pip show my_project and which python. Second, pyproject.toml or the layout is wrong, for example a missing __init__.py or no where = ["src"] setting, so an install succeeds without exposing the package. Check with python -c "import my_project; print(my_project.__file__)" and confirm the path points into src/my_project. Your own run may pass only because you installed it earlier or run from a directory that hides the problem. With the src/ layout, a broken install shows up as exactly this error.