Overview
This guide covers modern Python project setup including:
pyproject.tomlconfiguration (replacingsetup.pyandrequirements.txt)- Development dependencies separation (test/doc dependencies)
- Code quality tools (Ruff for linting/formatting, Mypy for type checking)
- Docker Compose for services with PostgreSQL
pyproject.toml - The Modern Standard
pyproject.toml is the modern standard for Python project configuration (PEP 518, 517, 621). It replaces setup.py, setup.cfg, and requirements.txt in a single unified file.
Basic Structure
[build-system]
requires = ["setuptools>=61.0", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "my-api-service"
version = "0.1.0"
description = "FastAPI service with LLM integration"
readme = "README.md"
requires-python = ">=3.11"
license = {text = "MIT"}
authors = [
{name = "Your Name", email = "[email protected]"}
]
# Core dependencies
dependencies = [
"fastapi>=0.104.0",
"hypercorn>=0.15.0",
"tiktoken>=0.5.0",
"json-repair>=0.28.0",
"jinja2>=3.1.0",
"sqlalchemy>=2.0.0",
"openai>=1.0.0",
"psycopg2-binary>=2.9.0",
]
[project.optional-dependencies]
# Development dependencies
dev = [
"pytest>=7.4.0",
"pytest-cov>=4.1.0",
"pytest-asyncio>=0.21.0",
"httpx>=0.25.0", # For testing FastAPI
]
# Documentation dependencies
docs = [
"sphinx>=7.0.0",
"sphinx-rtd-theme>=1.3.0",
]
# Linting and type checking
lint = [
"ruff>=0.1.0",
"mypy>=1.7.0",
]
# All development tools
all = [
"my-api-service[dev,docs,lint]",
]
[project.scripts]
# CLI entry points
my-api = "my_api_service.main:run"
[project.urls]
Homepage = "https://github.com/yourname/my-api-service"
Documentation = "https://my-api-service.readthedocs.io"
Repository = "https://github.com/yourname/my-api-service"
Installing with Optional Dependencies
# Install core dependencies only (production)
pip install .
# Install with development dependencies
pip install -e ".[dev]"
# Install with all development tools
pip install -e ".[all]"
# Install specific groups
pip install -e ".[dev,lint]"
The -e flag installs in "editable" mode, meaning changes to source code take effect immediately without reinstalling.
Doctest Dependencies - Production vs Development
๐ Note: By default, doctests embedded in docstrings are NOT run during production builds. They are only executed when you explicitly run test commands.
When Doctests Run
Doctests are executed in these scenarios:
- Running
pytest --doctest-modules - Running
python -m doctest module.py - CI/CD pipelines with test stages
When Doctests Do NOT Run
pip install .(production install)python -m my_module(running the module)- Docker production builds
Example Doctest
def calculate_tokens(text: str) -> int:
"""
Calculate the number of tokens in text using tiktoken.
Examples:
>>> calculate_tokens("Hello world")
2
>>> calculate_tokens("")
0
"""
import tiktoken
encoder = tiktoken.get_encoding("cl100k_base")
return len(encoder.encode(text))
The doctest dependencies (like tiktoken in this example) need to be in your core dependencies if the function uses them at runtime. If a dependency is ONLY used in doctest examples but not in the actual function, it should be in dev dependencies.
Ruff - Linting and Formatting
Ruff is an extremely fast Python linter and formatter written in Rust. It replaces multiple tools:
- Flake8 (style guide enforcement)
- isort (import sorting)
- Black (code formatting)
- And many more...
Ruff Configuration in pyproject.toml
[tool.ruff]
# Target Python version
target-version = "py311"
# Line length
line-length = 88
# Exclude directories
exclude = [
".git",
".venv",
"__pycache__",
"build",
"dist",
]
[tool.ruff.lint]
# Enable rules
select = [
"E", # pycodestyle errors
"W", # pycodestyle warnings
"F", # Pyflakes
"I", # isort
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"UP", # pyupgrade
"ARG", # flake8-unused-arguments
"SIM", # flake8-simplify
]
# Ignore specific rules
ignore = [
"E501", # line too long (handled by formatter)
"B008", # do not perform function calls in argument defaults
]
[tool.ruff.lint.per-file-ignores]
# Ignore unused imports in __init__.py
"__init__.py" = ["F401"]
# Ignore all in tests
"tests/**" = ["ARG", "S101"]
[tool.ruff.format]
# Use double quotes
quote-style = "double"
# Indent with spaces
indent-style = "space"
Running Ruff
# Check for linting errors
ruff check .
# Fix auto-fixable issues
ruff check --fix .
# Format code
ruff format .
# Check formatting without changing files
ruff format --check .
Mypy - Static Type Checking
Mypy performs static type analysis on Python code. It catches type errors before runtime.
Mypy Configuration in pyproject.toml
[tool.mypy]
python_version = "3.11"
# Strict mode options
strict = true
warn_return_any = true
warn_unused_ignores = true
disallow_untyped_defs = true
disallow_incomplete_defs = true
# Show error codes
show_error_codes = true
# Exclude directories
exclude = [
"tests/",
"build/",
"dist/",
]
# Per-module configuration
[[tool.mypy.overrides]]
module = "tests.*"
disallow_untyped_defs = false
[[tool.mypy.overrides]]
module = [
"tiktoken.*",
"json_repair.*",
]
ignore_missing_imports = true
Running Mypy
# Check entire project
mypy src/
# Check specific file
mypy src/my_module.py
# Generate HTML report
mypy src/ --html-report mypy_report
Type Hints Examples
from typing import Optional, List, Dict, Any
from collections.abc import Callable
def process_prompt(
template: str,
variables: Dict[str, Any],
max_tokens: Optional[int] = None,
) -> str:
"""Process a Jinja template with variables."""
from jinja2 import Template
rendered = Template(template).render(**variables)
return rendered
async def fetch_completion(
messages: List[Dict[str, str]],
callback: Optional[Callable[[str], None]] = None,
) -> str:
"""Fetch completion from OpenAI."""
...
Pytest Configuration
[tool.pytest.ini_options]
minversion = "7.0"
testpaths = ["tests"]
python_files = ["test_*.py", "*_test.py"]
python_functions = ["test_*"]
# Asyncio mode
asyncio_mode = "auto"
# Add options
addopts = [
"-v",
"--tb=short",
"--strict-markers",
"-ra",
]
# Markers
markers = [
"slow: marks tests as slow",
"integration: marks tests as integration tests",
]
# Coverage options
[tool.coverage.run]
source = ["src"]
branch = true
omit = ["tests/*", "*/__init__.py"]
[tool.coverage.report]
exclude_lines = [
"pragma: no cover",
"def __repr__",
"raise NotImplementedError",
"if TYPE_CHECKING:",
]
Docker Compose Setup
compose.yml - Production Services
services:
api:
build:
context: .
dockerfile: Dockerfile
ports:
- "8000:8000"
environment:
- DATABASE_URL=postgresql://user:password@db:5432/myapp
- OPENAI_API_KEY=${OPENAI_API_KEY}
depends_on:
db:
condition: service_healthy
restart: unless-stopped
db:
image: postgres:16-alpine
volumes:
- postgres_data:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
environment:
- POSTGRES_USER=user
- POSTGRES_PASSWORD=password
- POSTGRES_DB=myapp
ports:
- "5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U user -d myapp"]
interval: 5s
timeout: 5s
retries: 5
volumes:
postgres_data:
compose.test-deps.yml - Test Dependencies
This file provides external services needed for integration tests but NOT the application itself.
# compose.test-deps.yml
# Usage: docker compose -f compose.test-deps.yml up -d
services:
test-db:
image: postgres:16-alpine
ports:
- "5433:5432" # Different port to avoid conflict with dev DB
environment:
- POSTGRES_USER=testuser
- POSTGRES_PASSWORD=testpass
- POSTGRES_DB=testdb
tmpfs:
- /var/lib/postgresql/data # Use tmpfs for faster tests
healthcheck:
test: ["CMD-SHELL", "pg_isready -U testuser -d testdb"]
interval: 2s
timeout: 2s
retries: 10
test-redis:
image: redis:7-alpine
ports:
- "6380:6379" # Different port to avoid conflict
command: redis-server --appendonly no # Faster for tests
How to Use compose.test-deps.yml
# Start test dependencies before running tests
docker compose -f compose.test-deps.yml up -d
# Wait for services to be healthy
docker compose -f compose.test-deps.yml ps
# Run tests (pointing to test services)
DATABASE_URL=postgresql://testuser:testpass@localhost:5433/testdb pytest
# Run specific integration tests
DATABASE_URL=postgresql://testuser:testpass@localhost:5433/testdb \
pytest tests/integration/ -m integration
# Stop test dependencies
docker compose -f compose.test-deps.yml down
# Stop and remove volumes (clean slate)
docker compose -f compose.test-deps.yml down -v
CI/CD Integration
In GitHub Actions or other CI systems:
# .github/workflows/test.yml
name: Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16-alpine
env:
POSTGRES_USER: testuser
POSTGRES_PASSWORD: testpass
POSTGRES_DB: testdb
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install dependencies
run: pip install -e ".[dev,lint]"
- name: Lint with Ruff
run: |
ruff check .
ruff format --check .
- name: Type check with Mypy
run: mypy src/
- name: Run tests
env:
DATABASE_URL: postgresql://testuser:testpass@localhost:5432/testdb
run: pytest --cov=src --cov-report=xml
Dockerfile for Production
# Dockerfile
FROM python:3.11-slim as builder
WORKDIR /app
# Install build dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential \
&& rm -rf /var/lib/apt/lists/*
# Copy only dependency files first (layer caching)
COPY pyproject.toml .
COPY src/ src/
# Install production dependencies only
RUN pip install --no-cache-dir .
# Production stage
FROM python:3.11-slim
WORKDIR /app
# Copy installed packages from builder
COPY --from=builder /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin
# Copy application code
COPY src/ src/
# Create non-root user
RUN useradd -m -u 1000 appuser && chown -R appuser:appuser /app
USER appuser
EXPOSE 8000
CMD ["hypercorn", "src.main:app", "--bind", "0.0.0.0:8000"]
Complete pyproject.toml Example
Here's a complete example for a FastAPI + LLM service:
# =============================================================================
# BUILD SYSTEM - Defines how to build the package
# =============================================================================
[build-system]
# Packages required to build this project (not runtime dependencies)
requires = ["setuptools>=61.0", "wheel"]
# The build backend to use (setuptools is the most common)
build-backend = "setuptools.build_meta"
# =============================================================================
# PROJECT METADATA - Core project information (PEP 621)
# =============================================================================
[project]
# Package name on PyPI (use hyphens, not underscores)
name = "my-llm-api"
# Semantic versioning: MAJOR.MINOR.PATCH
version = "0.1.0"
# One-line description shown on PyPI
description = "FastAPI service with LLM integration"
# Path to README file (supports .md, .rst, .txt)
readme = "README.md"
# Minimum Python version required
requires-python = ">=3.11"
# License identifier
license = {text = "MIT"}
# Runtime dependencies - installed with `pip install .`
# These are REQUIRED for the package to function
dependencies = [
# Web framework - FastAPI for async API, Hypercorn as ASGI server
"fastapi>=0.104.0", # Async web framework
"hypercorn>=0.15.0", # ASGI server (alternative to uvicorn)
# LLM tools
"tiktoken>=0.5.0", # OpenAI tokenizer for counting tokens
"openai>=1.0.0", # Official OpenAI Python client
# Data processing
"json-repair>=0.28.0", # Fix malformed JSON from LLM outputs
"jinja2>=3.1.0", # Template engine for prompt building
# Database
"sqlalchemy>=2.0.0", # ORM and database toolkit
"psycopg2-binary>=2.9.0", # PostgreSQL adapter (binary for easy install)
]
# =============================================================================
# OPTIONAL DEPENDENCIES - Installed with `pip install .[group]`
# =============================================================================
[project.optional-dependencies]
# Development/testing dependencies: pip install -e ".[dev]"
dev = [
"pytest>=7.4.0", # Testing framework
"pytest-cov>=4.1.0", # Coverage plugin for pytest
"pytest-asyncio>=0.21.0", # Async test support
"httpx>=0.25.0", # Async HTTP client for testing FastAPI
]
# Documentation dependencies: pip install -e ".[docs]"
docs = [
"sphinx>=7.0.0", # Documentation generator
"sphinx-rtd-theme>=1.3.0", # Read the Docs theme
]
# Linting and type checking: pip install -e ".[lint]"
lint = [
"ruff>=0.1.0", # Fast linter and formatter (replaces flake8, black, isort)
"mypy>=1.7.0", # Static type checker
]
# All development tools: pip install -e ".[all]"
# References other groups using self-referential syntax
all = [
"my-llm-api[dev,docs,lint]",
]
# =============================================================================
# SETUPTOOLS CONFIGURATION - Package discovery
# =============================================================================
[tool.setuptools.packages.find]
# Look for packages in the "src" directory (src layout)
# This means your code lives in src/my_llm_api/
where = ["src"]
# =============================================================================
# RUFF - Fast Python linter and formatter (replaces flake8, black, isort)
# =============================================================================
[tool.ruff]
# Target Python version for syntax checks
target-version = "py311"
# Maximum line length (88 is black's default)
line-length = 88
# Directories to exclude from linting
exclude = [".git", ".venv", "__pycache__", "build", "dist"]
[tool.ruff.lint]
# Rule codes to enable:
# E = pycodestyle errors (indentation, whitespace, etc.)
# W = pycodestyle warnings
# F = Pyflakes (undefined names, unused imports, etc.)
# I = isort (import sorting)
# B = flake8-bugbear (common bugs and design problems)
# C4 = flake8-comprehensions (unnecessary list/dict/set calls)
# UP = pyupgrade (upgrade syntax for newer Python)
# ARG = flake8-unused-arguments
# SIM = flake8-simplify (simplifiable code)
select = ["E", "W", "F", "I", "B", "C4", "UP", "ARG", "SIM"]
# Rules to ignore:
# E501 = line too long (formatter handles this)
# B008 = function calls in default arguments (common in FastAPI: Depends())
ignore = ["E501", "B008"]
[tool.ruff.lint.per-file-ignores]
# F401 = unused import (ok in __init__.py for re-exports)
"__init__.py" = ["F401"]
# ARG = unused arguments (ok in tests for fixtures)
# S101 = use of assert (ok in tests)
"tests/**" = ["ARG", "S101"]
[tool.ruff.format]
# String quote style: "double" or "single"
quote-style = "double"
# Indentation: "space" or "tab"
indent-style = "space"
# =============================================================================
# MYPY - Static type checker
# =============================================================================
[tool.mypy]
# Python version for type checking
python_version = "3.11"
# Enable all strict mode checks (recommended for new projects)
# Includes: disallow_untyped_defs, disallow_incomplete_defs, etc.
strict = true
# Show error codes in output (e.g., [arg-type], [return-value])
show_error_codes = true
# Directories to exclude from type checking
exclude = ["tests/", "build/", "dist/"]
# Per-module overrides for third-party packages without type stubs
[[tool.mypy.overrides]]
# These packages don't have type annotations or stubs
module = ["tiktoken.*", "json_repair.*"]
# Don't error on missing type info for these modules
ignore_missing_imports = true
# =============================================================================
# PYTEST - Testing framework configuration
# =============================================================================
[tool.pytest.ini_options]
# Minimum pytest version required
minversion = "7.0"
# Directories to search for tests
testpaths = ["tests"]
# pytest-asyncio mode: "auto" automatically handles async tests
asyncio_mode = "auto"
# Default command-line options:
# -v = verbose output
# --tb=short = shorter tracebacks
# -ra = show summary of all non-passed tests
addopts = ["-v", "--tb=short", "-ra"]
# =============================================================================
# COVERAGE - Code coverage configuration
# =============================================================================
[tool.coverage.run]
# Directories to measure coverage for
source = ["src"]
# Enable branch coverage (if/else paths)
branch = true
Quick Reference: Project Structure
There are two approaches to testing: doctests only (simpler) or doctests + test directory (more powerful).
Option 1: Doctest-Only Structure (Simpler)
Best for: libraries, utilities, small projects where examples in docstrings suffice.
my-project/
โ
โโโ src/ # Source code directory (src layout)
โ โโโ my_package/
โ โโโ __init__.py
โ โโโ main.py # Tests live inside docstrings
โ โโโ utils.py # Each function has doctest examples
โ
โโโ pyproject.toml # Configure pytest to run doctests
โโโ Dockerfile
โโโ .gitignore
โโโ README.md
Example with doctests:
# src/my_package/utils.py
def calculate_tokens(text: str) -> int:
"""
Calculate the number of tokens in text.
Examples:
>>> calculate_tokens("Hello world")
2
>>> calculate_tokens("")
0
>>> calculate_tokens("This is a longer sentence with more tokens")
8
"""
import tiktoken
encoder = tiktoken.get_encoding("cl100k_base")
return len(encoder.encode(text))
pyproject.toml for doctest-only:
[tool.pytest.ini_options]
minversion = "7.0"
# Run doctests from all modules in src/
addopts = ["--doctest-modules", "-v"]
# Tell pytest where to find modules
pythonpath = ["src"]
Run tests:
pytest # Runs all doctests in src/
pytest --doctest-modules src/ # Explicit path
Option 2: Doctests + Test Directory (More Powerful)
Best for: applications, APIs, projects needing fixtures, mocks, integration tests.
my-project/
โ
โโโ src/ # Source code directory (src layout)
โ โ # Prevents accidental imports from project root
โ โ # Forces you to install package to test it
โ โ
โ โโโ my_package/ # Your actual Python package (use underscores)
โ โ # This name is used for imports: `import my_package`
โ โ
โ โโโ __init__.py # Makes this directory a Python package
โ โ # Can be empty or contain package-level exports
โ โ # Example: `from .main import app`
โ โ
โ โโโ main.py # Application entry point + simple doctests
โ โ # Contains FastAPI app, CLI logic, etc.
โ โ
โ โโโ utils.py # Utility/helper functions + doctests
โ # Add more modules as needed (models.py, api.py, etc.)
โ
โโโ tests/ # Test directory for complex tests
โ โ # Mirrors src/ structure for larger projects
โ โ
โ โโโ __init__.py # Makes tests a package (needed for some pytest configs)
โ โ
โ โโโ conftest.py # Pytest fixtures shared across all tests
โ โ # Database connections, test clients, mock data, etc.
โ โ
โ โโโ test_main.py # Tests for main.py (prefix with test_)
โ # Add test_utils.py, test_api.py, etc.
โ
โโโ pyproject.toml # Project configuration (replaces setup.py + requirements.txt)
โ # Dependencies, build config, tool settings (ruff, mypy, pytest)
โ
โโโ compose.yml # Docker Compose for production/development services
โ # Defines app container + database + other services
โ
โโโ compose.test-deps.yml # Docker Compose for test dependencies ONLY
โ # Spins up isolated test database, redis, etc.
โ # Uses different ports to avoid conflicts
โ
โโโ Dockerfile # Container build instructions
โ # Multi-stage build: builder stage + slim production stage
โ
โโโ .gitignore # Files/directories to exclude from git
โ # .venv/, __pycache__/, .env, dist/, *.egg-info/
โ
โโโ README.md # Project documentation
# Installation, usage, API docs, contributing guide
Doctests vs Test Directory: When to Use Which
| Aspect | Doctests | tests/ Directory |
|---|---|---|
| Location | Inside docstrings | Separate test files |
| Purpose | Simple examples, documentation | Complex test cases, edge cases |
| Scope | Single function demos | Integration tests, fixtures, mocks |
| Best for | "How to use this function" | "Does this work correctly in all scenarios" |
| Fixtures | Not supported | Full pytest fixture support |
| Mocking | Limited | Full mock/patch support |
| Async | Awkward | Native pytest-asyncio support |
Use doctests for:
- Pure functions with simple inputs/outputs
- Documentation examples that should stay accurate
- Quick sanity checks
Use tests/ directory for:
- Database/API integration tests
- Tests requiring fixtures (test clients, mock data)
- Parametrized tests with many cases
- Async endpoint testing
- Error handling and edge cases
Example: tests/ for complex scenarios
# tests/conftest.py
import pytest
from httpx import AsyncClient
from my_package.main import app
@pytest.fixture
async def client():
async with AsyncClient(app=app, base_url="http://test") as ac:
yield ac
@pytest.fixture
def mock_openai(mocker):
return mocker.patch("my_package.llm.openai.ChatCompletion.create")
# tests/test_api.py
import pytest
@pytest.mark.asyncio
async def test_generate_endpoint(client, mock_openai):
mock_openai.return_value = {"choices": [{"message": {"content": "Hello"}}]}
response = await client.post("/generate", json={"prompt": "Hi"})
assert response.status_code == 200
assert response.json()["result"] == "Hello"
@pytest.mark.parametrize("invalid_input", [None, "", {"wrong": "format"}])
async def test_generate_validation(client, invalid_input):
response = await client.post("/generate", json=invalid_input)
assert response.status_code == 422
Why src/ Layout?
The src/ layout is recommended over flat layout for these reasons:
- Prevents accidental imports - You can't
import my_packagefrom project root without installing - Forces proper installation - Ensures your package works the same in dev and production
- Cleaner root directory - Separates code from config files
- Avoids path manipulation - No need for
sys.pathhacks
# Flat layout (NOT recommended)
my-project/
โโโ my_package/ # Can be imported without installing!
โโโ tests/
โโโ pyproject.toml
# Src layout (recommended)
my-project/
โโโ src/
โ โโโ my_package/ # Must install to import
โโโ tests/
โโโ pyproject.toml
Commands Cheatsheet
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # Unix
.venv\Scripts\activate # Windows
# Install with all dev dependencies
pip install -e ".[all]"
# Run quality checks
ruff check . # Linting
ruff format --check . # Format check
mypy src/ # Type checking
# Run tests
pytest # All tests
pytest --cov=src # With coverage
pytest -m "not slow" # Skip slow tests
# Docker
docker compose up -d # Start services
docker compose -f compose.test-deps.yml up -d # Start test deps
docker compose down -v # Stop and clean
# Build and publish
pip install build twine
python -m build
twine upload dist/*
Summary
| Tool | Purpose |
|---|---|
| pyproject.toml | Unified project configuration |
| Ruff | Fast linting + formatting (replaces flake8, black, isort) |
| Mypy | Static type checking |
| pytest | Testing framework |
| Docker Compose | Service orchestration |
| compose.test-deps.yml | External deps for testing |
๐ก Tip: Run
ruff check --fix . && ruff format . && mypy src/before committing to catch issues early.