Python Core Development
Comprehensive guidance for modern Python development with focus on FastAPI, type safety, and best practices.
Quick Reference Guide
By Task Type
Getting Started
- New Project: Use
scripts/init_python_project.shfor FastAPI or package projects - Core Principles: See references/principles.md for PEP 8 and Python philosophy
- Common Errors: See references/common-errors.md for solutions
Writing Code
- Type Hints: See references/type-hints.md for annotations and mypy
- Async Programming: See references/async-patterns.md for asyncio patterns
- Testing: See references/testing.md for pytest strategies
Web Development (FastAPI)
- FastAPI Guide: See references/fastapi-guide.md for comprehensive tutorial
- Essential Libraries: See references/common-libraries.md
Code Quality
- Code Review: See references/code-review.md for checklist
- Performance: See references/performance.md for optimization
Project Management
- Dependencies: See references/dependencies.md for pip, poetry, uv
- Project Structure: See references/project-structure.md
By Question Type
| Question | Reference |
|---|---|
| "How do I build a FastAPI app?" | fastapi-guide.md |
| "How do I add type hints?" | type-hints.md |
| "How do I use async/await?" | async-patterns.md |
| "How do I test this?" | testing.md |
| "What are Python best practices?" | principles.md |
| "How do I structure my project?" | project-structure.md |
| "What libraries should I use?" | common-libraries.md |
| "How do I manage dependencies?" | dependencies.md |
| "How do I improve performance?" | performance.md |
| "Why am I getting this error?" | common-errors.md |
Core Workflows
1. Starting a FastAPI Project
Initialize Project
./scripts/init_python_project.sh my-api fastapi cd my-apiSet Up Environment
python -m venv venv source venv/bin/activate # or `venv\Scripts\activate` on Windows pip install fastapi uvicorn[standard] sqlalchemy pydantic pip install pytest mypy ruff --devConfigure Tools
- Copy
assets/configs/ruff.tomlfor linting - Copy
assets/configs/mypy.inifor type checking - Copy
assets/configs/pytest.inifor testing
- Copy
Start Development
uvicorn app.main:app --reloadVisit
http://localhost:8000/docsfor automatic API documentation
2. Building a FastAPI Endpoint
Define Pydantic Models
from pydantic import BaseModel, EmailStr class UserCreate(BaseModel): username: str email: EmailStr password: str class User(BaseModel): id: int username: str email: EmailStr is_active: bool = TrueCreate Endpoint
from fastapi import FastAPI, Depends, HTTPException from sqlalchemy.orm import Session app = FastAPI() @app.post("/users/", response_model=User) async def create_user( user: UserCreate, db: Session = Depends(get_db) ): db_user = crud.create_user(db, user) return db_userAdd Tests
from fastapi.testclient import TestClient def test_create_user(): response = client.post( "/users/", json={"username": "test", "email": "test@example.com", "password": "secret"} ) assert response.status_code == 200 assert response.json()["username"] == "test"
3. Code Quality Workflow
Type Check
mypy app/Lint and Format
ruff check app/ ruff format app/Run Tests
pytest --cov=appSecurity Audit
./scripts/audit_dependencies.sh
Decision Guides
When to Use FastAPI vs Django vs Flask
Use FastAPI when:
- Building modern REST APIs
- Need automatic OpenAPI/Swagger docs
- Want async/await support
- Type safety is important
- Performance is critical
Use Django when:
- Building full-stack web applications
- Need admin interface out of the box
- Want ORM with migrations
- Building monolithic applications
Use Flask when:
- Need maximum flexibility
- Building small to medium APIs
- Want lightweight framework
- Learning web development
See fastapi-guide.md for comprehensive FastAPI patterns.
Type Hints Strategy
Always use type hints for:
- Public function signatures
- Class attributes
- Function return types
- Complex data structures
Example:
from typing import Optional
def process_data(
items: list[str],
filter_fn: Optional[callable] = None
) -> dict[str, int]:
"""Process items and return counts."""
return {item: len(item) for item in items}
See type-hints.md for advanced patterns.
Async vs Sync
Use async when:
- I/O-bound operations (HTTP requests, database queries)
- Need high concurrency
- Using FastAPI (built for async)
- Working with async libraries (httpx, asyncpg)
Use sync when:
- CPU-bound operations
- Simple scripts
- Libraries don't support async
- Complexity isn't justified
See async-patterns.md for asyncio patterns.
Automation Scripts
scripts/init_python_project.sh
Initialize a new Python project with best practices:
- FastAPI or package structure
- pyproject.toml with modern config
- Development dependencies (pytest, mypy, ruff)
- Proper .gitignore
Usage: ./scripts/init_python_project.sh my-project [package|fastapi]
scripts/audit_dependencies.sh
Audit dependencies for security vulnerabilities:
- Runs pip-audit for known CVEs
- Checks for outdated packages
Usage: ./scripts/audit_dependencies.sh
scripts/setup_logging.sh
Set up structured logging with structlog:
- Installs structlog
- Creates configuration file
- JSON logging for production
Usage: ./scripts/setup_logging.sh
Configuration Templates
assets/configs/ruff.toml
Modern Python linter and formatter configuration:
- 100 character line length
- Comprehensive rule selection
- Import sorting
assets/configs/mypy.ini
Static type checker configuration:
- Strict mode enabled
- Python 3.11+ features
- Comprehensive warnings
assets/configs/pytest.ini
Testing framework configuration:
- Coverage reporting
- Async test support
- HTML coverage reports
assets/configs/pyproject.toml
Complete project configuration template:
- FastAPI dependencies
- Development tools
- Tool configurations
Reference Documentation
Core Python
- principles.md - PEP 8, Zen of Python, best practices
- type-hints.md - Type annotations, mypy, protocols
- async-patterns.md - asyncio, async/await, concurrency
Development
- testing.md - pytest, fixtures, mocking, coverage
- project-structure.md - Package layout, src/ pattern
- dependencies.md - pip, poetry, uv, pyproject.toml
- performance.md - Profiling, optimization strategies
- code-review.md - Review checklist, anti-patterns
Web Development
- fastapi-guide.md - Comprehensive FastAPI tutorial
- common-libraries.md - Essential Python packages
Troubleshooting
- common-errors.md - Common mistakes and solutions
FastAPI Quick Start
# main.py
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI(title="My API")
class Item(BaseModel):
name: str
price: float
is_offer: bool = False
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.post("/items/")
async def create_item(item: Item):
return {"item_name": item.name, "item_price": item.price}
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
Run: uvicorn main:app --reload
Docs: http://localhost:8000/docs
Best Practices Summary
- Use type hints everywhere - Enable mypy strict mode
- Follow PEP 8 - Use ruff for linting and formatting
- Write tests - Aim for 80%+ coverage with pytest
- Use async for I/O - FastAPI is built for async
- Validate with Pydantic - Type-safe data validation
- Structure projects properly - Use src/ layout
- Document code - Docstrings and type hints
- Handle errors explicitly - Specific exception types
- Audit dependencies - Regular security checks
- Profile before optimizing - Measure, don't guess
Example: Complete FastAPI Application
See fastapi-guide.md for:
- Database integration with SQLAlchemy
- Authentication with JWT
- File uploads
- WebSocket support
- Background tasks
- Testing strategies
- Deployment patterns
- Project structure
When to Consult References
Load references progressively:
- Starting out: Read principles.md for Python fundamentals
- Building web API: Consult fastapi-guide.md
- Adding types: Reference type-hints.md
- Going async: See async-patterns.md
- Testing: Use testing.md
- Debugging: Check common-errors.md
- Reviewing: Use code-review.md checklist
- Optimizing: See performance.md
Don't load all references at once—consult them as needs arise.
Converted and distributed by TomeVault — claim your Tome and manage your conversions.