Python Standards
Auto-loads for projects with Python in their tech stack.
Metadata
| Field | Value |
|---|---|
| Type | context |
| Applies to | python, fastapi, django, flask, pytest, pydantic, sqlalchemy, celery, poetry, asyncio, aiohttp, httpx |
Core Principles
- Simplicity - Simple, understandable code
- Readability - Readability over cleverness
- Maintainability - Code that’s easy to maintain
- Testability - Code that’s easy to test
- DRY - Don’t Repeat Yourself
Naming Conventions
| Element | Convention | Example |
|---|---|---|
| Variables/Functions | snake_case | get_user_by_id, is_active |
| Classes | PascalCase | UserService, ApiClient |
| Constants | UPPER_SNAKE_CASE | MAX_RETRY_COUNT |
| Private | Prefix with _ | _internal_method |
| Files/Modules | snake_case | user_service.py |
Code Style
from dataclasses import dataclass
@dataclass
class User:
id: str
name: str
email: str
age: int | None = None
def get_user_by_id(user_id: str) -> User | None:
if not user_id:
raise ValueError("user_id cannot be empty")
# implementation...Best Practices
# Type hints everywhere
def process_items(items: list[str]) -> dict[str, int]:
return {item: len(item) for item in items}
# Pydantic for validation
from pydantic import BaseModel, Field
class UserCreate(BaseModel):
name: str = Field(..., min_length=2, max_length=50)
email: EmailStr
age: int | None = Field(None, ge=0, le=150)
# Prefer pathlib over os.path
from pathlib import Path
config_path = Path(__file__).parent / 'config.yaml'Async/Await
async def fetch_user(user_id: str) -> User | None:
async with httpx.AsyncClient() as client:
response = await client.get(f"/users/{user_id}")
return User(**response.json()) if response.status_code == 200 else None
# Gather for concurrent operations
async def fetch_all_users(user_ids: list[str]) -> list[User]:
tasks = [fetch_user(uid) for uid in user_ids]
return await asyncio.gather(*tasks)Recommended Tooling
| Tool | Purpose |
|---|---|
uv | Package manager (faster than pip/poetry) |
ruff | Linting (replaces flake8, isort, black) |
mypy or pyright | Type checking |
pytest | Testing with pytest-cov, pytest-asyncio |
Production Checklist
- Type hints everywhere
- Pydantic for validation
- Async for I/O operations
- Structured logging (not print)
- Environment variables via pydantic-settings
- Custom exceptions for domain errors
- Connection pooling for databases/HTTP