Python Coding Standards
Enterprise-level Python standards for teams building production services, APIs, data pipelines, and automation tooling. These rules apply to all Python code that ships to production.
Style and Formatting
Python style follows PEP 8 with minor enterprise adjustments. Use a formatter so teams do not debate whitespace in code reviews.
Recommended tools:
- black for formatting (non-negotiable, no configuration debates)
- isort for import ordering
- flake8 or ruff for linting
- mypy for static type checking
Enforce these in CI so every commit is consistent.
Naming Conventions
# Modules and packages use lowercase with underscores
# order_processor.py
# payment_gateway/
# Classes use PascalCase
class OrderProcessor:
pass
class PaymentGateway:
pass
# Functions and variables use snake_case
def get_order_by_id(order_id: str) -> Order:
pass
total_amount = calculate_total(line_items)
# Constants use SCREAMING_SNAKE_CASE
MAX_RETRY_ATTEMPTS = 3
DEFAULT_CURRENCY = "GBP"
# Private members are prefixed with single underscore
class OrderService:
def __init__(self) -> None:
self._repository = OrderRepository()
def _validate_payload(self, payload: dict) -> None:
pass
Folder and Project Structure
A clean layout separates concerns and makes large projects manageable.
src/
acme_orders/
__init__.py
api/
__init__.py
routes/
orders.py
health.py
middleware/
auth.py
logging.py
schemas/
order_schema.py
application/
__init__.py
commands/
create_order.py
queries/
get_order.py
services/
order_service.py
domain/
__init__.py
models/
order.py
order_line.py
events/
order_created.py
infrastructure/
__init__.py
repositories/
order_repository.py
external/
payment_provider.py
db/
session.py
config.py
main.py
tests/
unit/
test_order_service.py
integration/
test_order_api.py
pyproject.toml
.env.example
Dockerfile
Rule of thumb:
- api only knows about schemas and application layer
- application layer knows about domain, not infrastructure
- domain layer has no dependencies on frameworks or external tools
- infrastructure implements contracts from the application layer
Type Annotations
All production code must have type annotations. Use from __future__ import annotations for forward references when needed.
from __future__ import annotations
from uuid import UUID
from decimal import Decimal
def create_order(
customer_id: UUID,
items: list[OrderItem],
currency: str = "GBP",
) -> Order:
pass
# Use Optional only when None is a valid value
def find_order(order_id: UUID) -> Order | None:
pass
# Data classes or Pydantic models for structured data
from pydantic import BaseModel
class CreateOrderRequest(BaseModel):
customer_id: UUID
items: list[OrderItemRequest]
currency: str = "GBP"
Error Handling
Handle errors at the boundary. Let domain exceptions propagate and catch them once.
# Define domain exceptions
class OrderNotFoundError(Exception):
def __init__(self, order_id: UUID) -> None:
super().__init__(f"Order {order_id} was not found.")
# Raise early in service logic
def get_order(order_id: UUID) -> Order:
order = self._repository.find(order_id)
if order is None:
raise OrderNotFoundError(order_id)
return order
# Catch at the API boundary, not inside business logic
@router.get("/orders/{order_id}")
async def get_order(order_id: UUID) -> OrderResponse:
try:
order = order_service.get_order(order_id)
return OrderResponse.from_domain(order)
except OrderNotFoundError as exc:
raise HTTPException(status_code=404, detail=str(exc))
Never swallow exceptions silently:
# Avoid this
try:
process_order(order_id)
except Exception:
pass # masks all errors
# Prefer this
try:
process_order(order_id)
except Exception:
logger.exception("Failed to process order %s", order_id)
raise
Logging
Use structured logging with correlation context.
import logging
import structlog
logger = structlog.get_logger(__name__)
# Log events with named values for searchability
logger.info("order_created", order_id=str(order.id), customer_id=str(order.customer_id))
logger.warning("payment_retry", order_id=str(order.id), attempt=attempt)
logger.error("order_processing_failed", order_id=str(order.id), exc_info=True)
Log levels:
- DEBUG: detailed trace for local development only
- INFO: normal lifecycle events
- WARNING: recoverable issues or degraded state
- ERROR: failures needing attention
- CRITICAL: system-level failures
Dependency Injection
Avoid global state. Inject dependencies through constructors or FastAPI's Depends mechanism.
# Using FastAPI dependency injection
from fastapi import Depends
def get_order_repository() -> OrderRepository:
return OrderRepository(session=get_db_session())
@router.get("/orders/{order_id}")
async def get_order(
order_id: UUID,
repository: OrderRepository = Depends(get_order_repository),
) -> OrderResponse:
pass
Configuration Management
Never hardcode values. Use environment variables with strong validation.
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
database_url: str
payment_api_key: str
max_retry_attempts: int = 3
debug: bool = False
class Config:
env_file = ".env"
env_file_encoding = "utf-8"
settings = Settings()
Never commit .env files. Always commit .env.example with placeholder values.
Testing Expectations
Use pytest with clear Arrange-Act-Assert structure.
import pytest
def test_create_order_with_valid_request_returns_order_id(
order_service: OrderService,
mock_repository: MagicMock,
) -> None:
# Arrange
request = CreateOrderRequest(
customer_id=uuid4(),
items=[OrderItemRequest(sku="SKU001", quantity=2)],
)
mock_repository.save.return_value = None
# Act
result = order_service.create_order(request)
# Assert
assert result.order_id is not None
mock_repository.save.assert_called_once()
Common Pitfalls
- mutable default arguments in function signatures
- missing type annotations on functions used across modules
- catching bare
except:without logging - hardcoding secrets or environment-specific values
- business logic inside route handlers
Key Takeaways
- type annotations make code self-documenting and safe to refactor
- black and ruff enforce consistency automatically
- domain exceptions propagate; API layer catches and translates them
- inject all dependencies, never import global state
- tests cover behaviour, not implementation details