Creating a Python project boilerplate
The user wants a boilerplate for a data science project using Python, Jupyter, and Poetry. I should include a concise yet information-dense structure with examples like a directory layout and a pyproject.toml file specifying dependencies such as JupyterLab, NumPy, and others. Instructions on setup commands like poetry new, poetry add, and running Jupyter should be included as well. I might also touch on adding a Makefile for tasks, but I should avoid excessive details. I’ll keep it reasonably concise!Structuring a Python project boilerplate
I plan to break down the response into sections: first, I’ll provide a project layout tree; next, an example of pyproject.toml with dependencies. I will include an example source package with __init__.py and a configuration file. Then, I’ll mention a sample notebook path and a README snippet with installation commands for running Jupyter. Additionally, I'll focus on integrating ipykernel with Poetry, and highlight the correct syntax for dev-dependencies based on the Poetry version. It's important to assume Python is version 3.11 or higher.Proposing a project structure
I’m outlining a project structure with a pyproject.toml, README.md, and a few other essential files. I’ll include folders for notebooks, source code, data, and reports, ensuring things like the .gitignore and generated poetry.lock are noted. While this might seem a bit extensive, it aligns with typical data science project layouts, although not fully cookiecutter. I’ll keep explanations minimal but still provide useful commands like poetry init and examples of file structures. Also, I’ll use proper code block labels for clarity!Drafting a minimal example
I think it might be helpful to include a simple usage example in the notebook, like using from my_project.data.load import load_data. However, the user specifically requested project structure and not actual data science code, so I’ll keep it very minimal. I want to provide just enough to illustrate the point without overcomplicating things. I'll focus on ensuring that the structure is clear and easy to understand. Let's move forward with the draft! Below is a minimal but solid boilerplate for a Python data science project that uses Poetry for dependency management and Jupyter for notebooks.
1. Project structure
my_ds_project/
├─ pyproject.toml
├─ README.md
├─ .gitignore
├─ data/
│ ├─ raw/.gitkeep
│ ├─ interim/.gitkeep
│ └─ processed/.gitkeep
├─ notebooks/
│ └─ 01_exploration.ipynb
├─ src/
│ └─ my_ds_project/
│ ├─ __init__.py
│ ├─ config.py
│ ├─ data.py
│ ├─ features.py
│ ├─ modeling.py
│ └─ viz.py
└─ tests/
└─ test_sample.py
This follows a simplified version of the “cookiecutter data science” layout but tuned for Poetry + Jupyter.
2. pyproject.toml (Poetry config)
[tool.poetry]
name = "my-ds-project"
version = "0.1.0"
description = "Boilerplate Python data science project using Poetry and Jupyter"
authors = ["Your Name <you@example.com>"]
readme = "README.md"
packages = [{ include = "my_ds_project", from = "src" }]
[tool.poetry.dependencies]
python = "^3.11"
# Core DS stack
numpy = "^2.0.0"
pandas = "^2.2.0"
scipy = "^1.13.0"
scikit-learn = "^1.5.0"
# Plotting
matplotlib = "^3.9.0"
seaborn = "^0.13.0"
# Jupyter
jupyterlab = "^4.0.0"
ipykernel = "^6.0.0"
[tool.poetry.group.dev.dependencies]
pytest = "^8.0.0"
black = "^24.0.0"
ruff = "^0.6.0"
ipython = "^8.0.0"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
Adjust versions as needed; this is just a starting point.
3. .gitignore
# Byte-compiled / cache
__pycache__/
*.py[cod]
*.pyo
# Poetry
poetry.lock
# Jupyter
.ipynb_checkpoints/
*.ipynb~
# Data
data/raw/*
data/interim/*
data/processed/*
# OS / editor files
.DS_Store
*.swp
.idea/
.vscode/
If you want to commit example data, remove the data/* ignores or add exceptions.
4. Minimal src/ package files
src/my_ds_project/__init__.py
"""
my_ds_project: boilerplate data science package.
Exposes common functions for notebooks and scripts.
"""
__all__ = ["config", "data", "features", "modeling", "viz"]
src/my_ds_project/config.py
from pathlib import Path
# Project root is two levels up from this file: src/my_ds_project/config.py
PROJECT_ROOT = Path(__file__).resolve().parents[2]
DATA_DIR = PROJECT_ROOT / "data"
RAW_DATA_DIR = DATA_DIR / "raw"
INTERIM_DATA_DIR = DATA_DIR / "interim"
PROCESSED_DATA_DIR = DATA_DIR / "processed"
NOTEBOOKS_DIR = PROJECT_ROOT / "notebooks"
src/my_ds_project/data.py
from pathlib import Path
import pandas as pd
from .config import RAW_DATA_DIR, PROCESSED_DATA_DIR
def load_csv(name: str, folder: Path | None = None, **read_csv_kwargs) -> pd.DataFrame:
"""
Load a CSV from data/raw (or given folder).
Example:
df = load_csv("train.csv")
"""
folder = folder or RAW_DATA_DIR
path = folder / name
return pd.read_csv(path, **read_csv_kwargs)
def save_processed(df: pd.DataFrame, name: str, **to_csv_kwargs) -> None:
"""
Save a DataFrame to data/processed.
"""
PROCESSED_DATA_DIR.mkdir(parents=True, exist_ok=True)
path = PROCESSED_DATA_DIR / name
df.to_csv(path, index=False, **to_csv_kwargs)
src/my_ds_project/features.py
import pandas as pd
def add_basic_features(df: pd.DataFrame) -> pd.DataFrame:
"""
Example feature engineering function.
Modify as needed for your project.
"""
df = df.copy()
# Placeholder: add your features here
# e.g., df["feature_x"] = df["col_a"] / (df["col_b"] + 1)
return df
src/my_ds_project/modeling.py
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Tuple
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
@dataclass
class TrainConfig:
test_size: float = 0.2
random_state: int = 42
def train_simple_model(
df: pd.DataFrame, target_col: str, cfg: TrainConfig | None = None
) -> Tuple[BaseEstimator, dict[str, Any]]:
"""
Minimal example training function on tabular data.
"""
cfg = cfg or TrainConfig()
X = df.drop(columns=[target_col]).values
y = df[target_col].values
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=cfg.test_size, random_state=cfg.random_state
)
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
acc = accuracy_score(y_test, y_pred)
metrics = {"accuracy": acc}
return model, metrics
src/my_ds_project/viz.py
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
def plot_target_distribution(df: pd.DataFrame, target_col: str) -> None:
"""
Example plot function.
"""
plt.figure(figsize=(6, 4))
sns.countplot(x=target_col, data=df)
plt.title(f"Distribution of {target_col}")
plt.tight_layout()
plt.show()
5. Example test file
tests/test_sample.py
from my_ds_project.features import add_basic_features
import pandas as pd
def test_add_basic_features_does_not_change_shape():
df = pd.DataFrame({"a": [1, 2, 3]})
out = add_basic_features(df)
assert out.shape[0] == df.shape[0]
6. Installing and using Poetry
From the project root (my_ds_project/):
# Install dependencies
poetry install
# Activate a shell in the Poetry env
poetry shell
You can also run commands without entering the shell:
poetry run pytest
poetry run python -m my_ds_project.modeling
7. Using Jupyter with the Poetry environment
-
Install the kernel (once):
poetry run python -m ipykernel install --user \
--name my-ds-project \
--display-name "Python (my-ds-project)"
-
Launch JupyterLab from the project directory:
poetry run jupyter lab
-
In JupyterLab, select the kernel “Python (my-ds-project)” for your notebooks.
Inside a notebook, you can now import your package directly:
from my_ds_project.data import load_csv
from my_ds_project.features import add_basic_features
from my_ds_project.modeling import train_simple_model
from my_ds_project.viz import plot_target_distribution
8. Optional: minimal README.md
# my-ds-project
Boilerplate Python data science project using Poetry and Jupyter.
## Setup
```bash
poetry install
poetry run python -m ipykernel install --user \
--name my-ds-project \
--display-name "Python (my-ds-project)"
Usage
Launch JupyterLab:
poetry run jupyter lab
In notebooks, select the Python (my-ds-project) kernel and import:
from my_ds_project.data import load_csv
---
If you tell me your Python version and preferred libraries (e.g., PyTorch vs. pure sklearn), I can tweak this boilerplate more specifically to your stack.