Python Style Guide
Overview
Use this skill to review and improve Python code for correctness, readability, and production reliability.
Scope Boundaries
- Use this skill when the task matches the trigger condition described in
description. - Do not use this skill when the primary task falls outside this skill's domain.
Trigger Reference
- Use
references/trigger-matrix.mdas the canonical trigger and co-activation matrix. - Resolve skill activation from changed files with
python3 scripts/resolve_style_guides.py <changed-path>...when automation is available. - Validate trigger matrix consistency with
python3 scripts/validate_trigger_matrix_sync.py.
Quality Gate Reference
- Use
references/quality-gate-command-matrix.mdfor CI check-only vs local autofix command mapping.
Shared References
- Typing and boundary rules:
references/typing-and-boundary-rules.md
Templates And Assets
- Python review checklist:
assets/python-review-checklist.md
- Refactor plan template:
assets/python-refactor-plan-template.md
Inputs To Gather
- Changed modules and impacted boundaries.
- Typing and data-modeling risk hotspots.
- Error/config/security constraints.
- CI and runtime quality gate expectations.
Deliverables
- Risk-prioritized review findings.
- Refactor plan with validation strategy.
- Merge readiness decision with residual risks.
Workflow
- Confirm trigger fit and impacted Python artifacts.
- Plan changes via
assets/python-refactor-plan-template.md. - Review with
assets/python-review-checklist.mdand project gates. - Apply improvements for typing, boundaries, and failure visibility.
- Execute required checks and publish residual-risk ownership.
Review And Refactor Checklist
Architecture and module boundaries
- Keep modules cohesive and focused on one responsibility.
- Isolate side effects (I/O, network, DB) behind clear interfaces.
- Keep orchestration layers thin and move business rules into domain modules.
- Avoid circular imports by keeping dependency direction explicit.
Naming and code structure
- Follow PEP 8 naming conventions (
snake_case,PascalCase,UPPER_CASEconstants). - Write small functions with explicit inputs/outputs.
- Replace magic numbers with named constants including units (
REQUEST_TIMEOUT_SECONDS). - Add short comments only where intent is non-obvious.
Typing and data modeling
- Add type hints for public functions, methods, and complex locals.
- Prefer explicit models (
dataclass,TypedDict, Pydantic model) over loose dicts. - Avoid
Anyunless unavoidable and justified inline. - Define precise protocols/interfaces for pluggable dependencies.
- Avoid
dict[str, Any]andobjectfor domain payloads when structure is known. - Convert untyped external input into explicit models once at the boundary, then keep inner layers strongly shaped.
- Treat repeated
typing.cast(...)usage as a signal to redesign the underlying type contract.
Error handling and control flow
- Raise specific exception types with actionable messages.
- Catch exceptions intentionally at boundaries and preserve causal chains.
- Avoid broad
except Exceptionunless rethrowing after required cleanup/logging. - Do not suppress failures with silent fallback logic by default.
Configuration and environment
- Parse and validate configuration at startup.
- Fail startup when required environment variables are missing.
- Do not hardcode fallback defaults for required environment variables.
- Keep secrets in secret managers or injected environment, never in code.
Security and compliance
- Validate untrusted input at boundaries.
- Use parameterized DB queries; never build SQL with string concatenation.
- Avoid unsafe deserialization and command execution with unchecked input.
- Redact secrets and sensitive fields from logs.
Performance and efficiency
- Measure bottlenecks before optimizing (
cProfile, tracing, metrics). - Avoid N+1 data access patterns and repeated expensive computation.
- Stream large datasets instead of loading everything into memory.
- Use bounded retries/backoff with named constants.
Testing and verification
- Add unit tests for core logic and integration tests for boundaries.
- Cover edge cases: invalid data, timeout, retry exhaustion, concurrency hazards.
- Add regression tests for every bug fix.
- Document manual verification when automation cannot cover behavior.
Observability and operations
- Use structured logs with trace/request IDs.
- Emit metrics for latency, throughput, and errors.
- Normalize exception-to-error response mapping at API boundaries.
- Ensure alertable signals exist for critical failure paths.
CI required quality gates (check-only)
- Run
uv run ruff format --check .. - Run
uv run ruff check .. - Run
uv run mypy .(or project type checker equivalent). - Run
uv run pytest -q.
Optional autofix commands (local)
- Run
uv run ruff format .. - Run
uv run ruff check --fix ., then re-run checks.
Failure Conditions
- Stop when boundary contracts remain ambiguous after review.
- Stop when required configuration or typing guarantees are missing.
- Escalate when unresolved defects threaten correctness or operability.