Production-ready Python DOs and DON'Ts for engineers. Covers code quality, type hints, error handling, async patterns, testing, security, performance, logging, and data validation. Use when writing Python code that needs to be production-ready, reviewing Python code, refactoring legacy Python, or answering questions about Python best practices. Targets Python 3.12+.
Production-grade DOs and DON'Ts for Python 3.12+.
| Topic | Key Principle |
|---|---|
| Code Quality | Readable > clever |
| Type Hints | Type everything public |
| Error Handling | Catch specific, never silent |
| Async/Await |
| Never block the event loop |
| Testing | Test behavior, not implementation |
| Security | Never trust input |
| Project Structure | Use src layout |
| Performance | Measure first, optimize bottlenecks |
| Logging | Structured logs, appropriate levels |
| Data Validation | Validate at boundaries |
| Code Review | Blockers vs improvements |
Core Principle: Code is read more than written. Optimize for readability.
# Descriptive names
def calculate_discounted_price(original_price: float, discount_rate: float) -> float:
return original_price * (1 - discount_rate)
# Dataclasses for structured data
@dataclass
class User:
name: str
email: str
created_at: datetime
# Early returns reduce nesting
def get_user(user_id: int) -> User | None:
if not user_id:
return None
return database.get_user(user_id)
# Context managers for resources
with open("file.txt") as f:
content = f.read()
def calc(a, b): # Cryptic name
return a * b
user = {"nme": "Alice"} # Typos silently fail
f = open("file.txt") # Never closed
content = f.read()
See references/clean-code.md
Core Principle: Type all public interfaces.
def fetch_user(user_id: int) -> User | None: ...
type UserId = int
type JsonDict = dict[str, str | int | float]
def get_items[T](items: list[T]) -> list[T]: ...
class Renderable(Protocol):
def render(self) -> str: ...
def process(data: Any) -> Any: ... # Useless
from typing import Union
def old(x: Union[str, int]): ... # Use str | int
See references/type-hints.md
Core Principle: Catch specific exceptions, never silent failures.