| name | coding-standards |
| description | Python coding standards and best practices covering error handling, performance optimization, async patterns, SOLID design principles, documentation, data validation, and object-oriented programming. Use when writing, reviewing, or refactoring Python code, or when the user asks about Python style, design, or best practices. |
| paths | ["**/*.py","pyproject.toml","setup.py","requirements*.txt"] |
Python Coding Standards
A comprehensive collection of Python coding standards and best practices. Designed for AI agents and LLMs to generate high-quality, performant, and maintainable Python code.
Categories
Error Handling [CRITICAL]
Prevent failures from being hidden or reported as successful outcomes.
Performance Optimization [CRITICAL]
Apply Python optimization patterns to improve processing speed and memory efficiency.
Async Processing [HIGH]
Efficient asynchronous programming patterns using asyncio.
Design Principles [HIGH]
Software design principles for maintainability and extensibility.
Documentation [HIGH]
Documentation standards for public API clarity and machine-checkable contracts.
Data Validation [HIGH]
Validation patterns for data crossing trust boundaries.
Object-Oriented Programming [MEDIUM]
Best practices for Pythonic object-oriented programming.
Quick Reference
Error Handling
try:
config = parse_config(path)
except ConfigParseError as exc:
raise StartupError(f"Invalid configuration: {path}") from exc
def main() -> int:
try:
start_application()
except StartupError:
logger.exception("Application startup failed")
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
Performance Patterns
result = [x * 2 for x in items]
total = sum(x * x for x in range(1_000_000))
value = config.get("key", default_value)
valid_ids: set[int] = {1, 2, 3}
if item_id in valid_ids: ...
result = ",".join(values)
Async Patterns
results = await asyncio.gather(task1(), task2(), task3())
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
data = await response.json()
semaphore = asyncio.Semaphore(10)
async with semaphore:
await do_work()
Design Patterns
class Service:
def __init__(self, repository: Repository) -> None:
self.repository = repository
def create_app(settings: Settings) -> Service:
return Service(repository=PostgresRepository(settings.dsn))
class JsonFormat:
def export(self, invoice: Invoice) -> str: ...
class Workable(Protocol):
def work(self) -> None: ...
def process(data: Data | None) -> Result:
if data is None:
return Result.empty()
Documentation Patterns
def create_user(email: str, name: str) -> User:
"""Create a user account.
Args:
email: Unique email address for the account.
name: Display name for the user.
Returns:
The created user.
"""
return user_repository.create(email=email, name=name)
Validation Patterns
from pydantic import BaseModel, EmailStr, Field
class CreateUserRequest(BaseModel):
email: EmailStr
age: int = Field(ge=0, le=150)
OOP Patterns
@dataclass
class User:
name: str
email: str
class Repository(Protocol):
def get(self, id: str) -> Entity: ...
@property
def full_name(self) -> str:
return f"{self.first} {self.last}"
See Also
- Recommended Tooling - Tools to enforce these standards automatically (ruff, mypy, pytest, pyscn, uv)