Python course ยท Module 12: Final Project
Technical Documentation
In this lesson3
The best savanna guide is useless if their knowledge disappears with them. A new expedition member then gets only a copy of the tracks without a legend. Code works the same way: a project without documentation can be started by one person, and after three months even that person forgets how they did it. Documentation is the bridge between code and people. Good documentation keeps the project alive even while you sleep, and lets a recruiter or a new teammate understand it in five minutes.
We build documentation on three levels: a README for someone who sees the repository for the first time, docstrings for the person reading the code, and generated API documentation for those who use it. A good order of work is the README first, then docstrings, then configuring the generated API docs, and finally CHANGELOG.md, the log of changes across versions.
README.md - The Project's Business Card
The README is the first thing GitHub shows below the file list. A typical order of sections: title, description or features, quick start, and the license at the end. Here is a complete example for our assistant:
# AI Document Assistant
An intelligent assistant for searching documents using RAG.
## Features
- Semantic search across documents
- Answers in natural language
- Support for PDF, DOCX, TXT
- Fast responses (<2s)
## Quick Start
### Requirements
- Python 3.12+
- Docker (for Qdrant)
### Installation
```bash
# Clone the repo
git clone https://github.com/user/ai-doc-assistant.git
cd ai-doc-assistant
# Create environment
python -m venv venv
source venv/bin/activate
# Install dependencies
pip install -r requirements.txt
# Launch Qdrant
docker compose up -d qdrant
# Set environment variables
cp .env.example .env
# Edit .env and add OPENAI_API_KEY
# Run the application
uvicorn app.main:app --reload
```
## API Documentation
After launching: http://localhost:8000/docs
## Architecture
[Link to architecture diagram]
## Testing
```bash
pytest tests/ -v
```
## License
MITThe installation guide is a sequence of commands you can copy and run: clone, virtual environment, dependencies, database, environment variables, start. Pay attention to cp .env.example .env: real keys never go into the repository, only a template of the file. docker compose (with a space) is the current version of the tool, built into Docker as a plugin.
Docstrings - In-Code Documentation
A docstring is a string in triple quotes right below a class or function definition. PEP 257 describes the general conventions, and you choose the format of the sections. The most popular are Google style and NumPy style, both understood by Sphinx (the napoleon extension). We use Google style: the Attributes, Args, Returns, Raises and Example sections.
from typing import Optional
class RAGService:
"""
RAG service for answering questions based on documents.
This service implements the full RAG pipeline:
1. Embedding the question
2. Searching for similar documents
3. Generating a response with context
Attributes:
vector_store: Vector database client
llm: Language model client
embedder: Embedding service
Example:
>>> service = RAGService(vector_store, llm, embedder)
>>> response = await service.query("What is Python?")
>>> print(response.answer)
Python is a programming language...
"""The class docstring says what the service does and what it consists of. The example in >>> format shows usage, and the line below it is the printed result. The constructor is simple and needs no separate description:
def __init__(
self,
vector_store: VectorStore,
llm: LLMClient,
embedder: EmbeddingService
):
self.vector_store = vector_store
self.llm = llm
self.embedder = embedderThe argument types (VectorStore, LLMClient, EmbeddingService) are interfaces from the infrastructure layer, following the architecture from the previous lesson. The public method needs the most description:
async def query(
self,
question: str,
top_k: int = 5,
filters: Optional[dict] = None
) -> Response:
"""
Performs a RAG query.
Args:
question: User question in natural language
top_k: Number of documents to retrieve (default: 5)
filters: Optional metadata filters
Returns:
Response: Object containing the answer and sources
Raises:
ValueError: When the question is empty
LLMError: When a generation error occurs
Example:
>>> response = await service.query(
... "How does RAG work?",
... top_k=3,
... filters={"category": "ai"}
... )
"""
if not question.strip():
raise ValueError("Question cannot be empty")
# Implementation...The Raises section is often skipped, yet it is the one that tells you what can go wrong. You can read a docstring in the console with help(RAGService.query), so it is documentation that is always at hand. Note: the example with await is meant for reading, a plain doctest will not run it.
API Documentation with FastAPI
FastAPI generates API documentation in the OpenAPI standard (formerly Swagger) automatically, based on types and Pydantic models. First, the application metadata:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
app = FastAPI(
title="AI Document Assistant API",
description="REST API for an intelligent document assistant",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc"
)Under /docs you get the interactive Swagger UI, under /redoc the alternative ReDoc view. Now the request and response models. Pydantic validates the data, and Field adds constraints and descriptions:
class QueryRequest(BaseModel):
"""RAG query request."""
question: str = Field(
...,
description="Question in natural language",
examples=["What is machine learning?"]
)
top_k: int = Field(
default=5,
ge=1,
le=20,
description="Number of source documents"
)
class QueryResponse(BaseModel):
"""Response from the RAG system."""
answer: str = Field(description="Generated answer")
sources: list[dict] = Field(description="Source documents")
latency_ms: float = Field(description="Response time in ms")ge=1, le=20 means "from 1 to 20", so top_k=50 is rejected with a 422 error before it reaches your code. Example values are given with examples=[...]. The old example= parameter is deprecated in Pydantic v2 and produces a warning. Finally, the endpoint:
@app.post(
"/query",
response_model=QueryResponse,
summary="Ask a question",
description="Performs a RAG query and returns an answer with sources"
)
async def query(request: QueryRequest) -> QueryResponse:
"""
Endpoint for asking questions to the RAG system.
- **question**: Question in natural language
- **top_k**: Number of documents to search
"""
passsummary and description appear in Swagger UI, and so does the docstring with its markdown. You do not write any separate documentation file, the schema is built from the code, so it cannot drift away from reality.
My advice: write the README on the same day you create the repository, not at the end of the project. Documentation written as you go is shorter and more truthful. In the next lesson we move on to deployment.
Remember: documentation is the expedition journal that lets the next expedition follow your tracks without guessing.
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What format do Python docstrings use most often?
2. Which tool is most commonly used for REST API documentation?
Hands-on tasks in the game
- Code editor
Write a Python docstring for a class with a description of parameters and methods
- Vertical ordering
Arrange the elements of project documentation from most important to least important:
- Horizontal ordering
Arrange the basic README.md sections in the correct order: