python-coding-patterns
Python Coding Patterns
Produce production-ready Python with explicit contracts, stable boundaries, disciplined concurrency, and strong review standards. Use this skill for implementation, debugging, refactoring, and reviews where long-term maintainability matters as much as short-term correctness.
Purpose
Drive Python work through repeatable architecture and quality gates. Prevent common drift patterns such as untyped boundary spread, silent exception suppression, ad hoc asyncio usage, oversized modules, and weak test isolation. Preserve delivery speed while improving correctness and operational clarity.
Operating Mode
Start every task by selecting one mode.
implement
- Define boundary contracts first.
- Choose typing depth and validation strategy.
- Implement with explicit error and concurrency behavior.
debug
- Gather failure signal from traceback, test failure, runtime behavior, or profiling.
- Map symptom to design cause.
- Apply coherent fix and add regression coverage.
review
- Report findings first by severity.
- Explain runtime impact and triggering conditions.
- Recommend minimal corrective path.
refactor
- Preserve public behavior.
- Improve module boundaries, type clarity, and testability.
- Add tests that lock intended behavior.
Entry Checklist
Complete this checklist before code changes.
- Workload classification.
- CPU-heavy.
- I/O-heavy.
- Mixed.
- Correctness constraints.
- Domain invariants.
- Input/output schema rules.
- Failure classes and recovery expectations.
- Operational constraints.
- Latency/throughput expectations.
- Memory and queue limits.
- Cancellation and shutdown behavior.
- Compatibility constraints.
- API and payload stability.
- Migration impact.
- Dependency constraints.
Reference Loading Map
Load only the files needed for the task.
- Async orchestration and cancellation:
references/asyncio-patterns.md - Typing, architecture, errors, and performance:
references/core-patterns.md - Symptom-to-design troubleshooting:
references/error-to-design-map.md - Findings-first review rubric:
references/review-checklist.md - Domain-specific constraints:
references/domain-web.mdreferences/domain-cli.mdreferences/domain-data.md
Implementation Workflow
Follow this sequence unless constraints require variation.
- Define boundary contract.
- Specify accepted input models and output models.
- Make optionality explicit.
- Separate external payload shape from internal domain shape.
- Define typing strategy.
- Type public APIs and boundary adapters first.
- Use protocol-based interfaces for behavior contracts.
- Keep
Anylocalized and justified.
- Define validation strategy.
- Validate untrusted input at boundaries.
- Convert into typed internal representations.
- Reject invalid state early.
- Define error strategy.
- Use domain-specific exception taxonomy.
- Wrap lower-level exceptions with contextual intent.
- Separate user-facing error message from internal diagnostics.
- Define concurrency strategy.
- Use synchronous flow for simple CPU or linear logic.
- Use
asynciofor high-concurrency I/O paths. - Bound parallelism via semaphore or queue limits.
- Implement observability.
- Add structured logs around external boundaries.
- Include correlation identifiers for multi-step flows.
- Emit signals that support failure triage.
- Implement verification.
- Unit tests for core business logic.
- Integration tests for boundary adapters.
- Async tests for cancellation, timeout, and boundedness behavior.
Debugging Workflow
Use design-trace debugging instead of local patching.
- Capture primary signal.
- Traceback and failing test.
- Runtime event-loop warnings.
- Latency or memory regression.
- Type-checker diagnostics.
- Translate symptom to design question.
- Data model mismatch.
- Optionality and nullability drift.
- Async lifecycle unsupervised.
- Error handling too broad or too narrow.
- Apply coherent fix.
- Change boundary contract when model mismatch exists.
- Replace broad catch with typed error handling.
- Replace unsupervised tasks with structured orchestration.
- Add explicit timeout and retry policy.
- Verify and harden.
- Reproduce before and after behavior.
- Add regression tests.
- Confirm static typing and linting signals are clean.
Linting And Type Gates
Run these checks before declaring Python work complete.
- Formatting and lint.
ruff format --check .ruff check .
- Type checking.
pyright- If
pyrightis not on PATH, usepython -m pyrightor project script (for exampleuv run pyright).
- Tests.
- Run impacted tests first, then broader suite when risk is high.
- Fix policy.
- Prefer fixing root causes over adding ignores.
- Add ignore comments only with a short justification.
Review Workflow
Use findings-first review structure.
- Severity order.
- S0: security, data loss, critical outage risk.
- S1: correctness bug with user-visible impact.
- S2: reliability/performance/maintainability risk.
- S3: style and documentation.
- Finding structure.
- What is wrong.
- Why behavior is risky.
- How to trigger.
- Minimal remediation.
- Missing tests.
- Python-specific review lenses.
- Boundary typing quality.
- Validation completeness at trust boundaries.
- Exception taxonomy and context quality.
- Async cancellation and task supervision.
- Module cohesion and dependency direction.
- Hidden mutable defaults and shared state hazards.
- Evidence standard.
- Provide file/line pointers.
- Include concrete runtime path.
- Avoid speculative findings without trigger scenario.
Architecture Heuristics
Use these heuristics to keep codebases evolvable.
- Separate domain from transport.
- Keep business logic pure and framework-agnostic.
- Keep HTTP/CLI/queue adapters thin.
- Convert errors and payloads at boundaries.
- Keep modules cohesive.
- Group by capability, not by accidental utility sprawl.
- Keep side effects explicit and localized.
- Prefer dependency injection for testability.
- Keep interfaces narrow.
- Define protocol contracts on consumer side.
- Avoid broad manager-style classes.
- Prefer simple composable functions over deep inheritance.
- Keep state transitions explicit.
- Validate state changes in one place.
- Avoid hidden mutation across call graph.
- Treat global mutable state as exceptional.
Asyncio Principles
Apply these rules for reliable async Python.
- Supervise task lifecycles.
- Use structured concurrency when available.
- Track and await task completion intentionally.
- Treat orphan tasks as defects unless explicitly detached.
- Bound concurrency.
- Limit fan-out with semaphores.
- Use bounded queues for producer/consumer flows.
- Define overflow behavior explicitly.
- Make cancellation reliable.
- Treat cancellation as normal path.
- Use cleanup blocks and re-raise cancellation.
- Define timeout budget for shutdown.
- Protect loop health.
- Avoid blocking calls in async functions.
- Offload CPU-heavy work from event loop.
- Avoid high-frequency polling without backoff.
Error Strategy Principles
Standardize failure behavior across modules.
- Classify errors.
- Validation failures.
- Dependency/transient failures.
- Internal invariant failures.
- Preserve context.
- Add operation context at boundaries.
- Keep original cause linked for debugging.
- Map errors by boundary.
- API layer: stable response model.
- CLI layer: actionable terminal messages and exit codes.
- Worker layer: retry and dead-letter policy signals.
- Avoid anti-patterns.
- Bare
except. - Silent pass on errors.
- Error-only string protocol matching.
Performance Workflow
Optimize only after measurement.
- Measure baseline.
- Latency and throughput.
- Memory profile.
- Hotspot and allocation profile.
- Optimize in order.
- Algorithm and data structure.
- Serialization and object churn.
- I/O parallelism and batching.
- Localized micro-optimizations.
- Verify tradeoffs.
- Preserve behavior with tests.
- Re-run benchmark under representative load.
- Document complexity and readability impact.
Tooling and Verification Baseline
Apply these quality gates before finalizing work.
- Format check.
- Lint check.
- Type checker pass.
- Unit and integration tests.
- Async edge-case tests for cancellation, timeout, and boundedness.
Prefer project-standard tooling. Use configured tools from repository before introducing alternatives.
Deliverable Format
Return outputs in this order.
- Design summary.
- Typing strategy.
- Validation boundaries.
- Error model.
- Concurrency model.
- Implementation summary.
- Files changed.
- Behavioral impact.
- Compatibility notes.
- Risk notes.
- Remaining hazards.
- Runtime assumptions.
- Monitoring hooks.
- Verification summary.
- Commands run.
- Tests added/updated.
- Known gaps.
Anti-Drift Rules
Apply these rules during maintenance.
- Reject untyped boundary spread in shared modules.
- Reject broad exception handling without rationale.
- Reject unbounded async fan-out in service paths.
- Reject hidden global mutable state.
- Reject large behavior changes without regression tests.
Scenario Playbooks
Use these playbooks for frequent workflows.
- Add a new API endpoint with validation.
- Define request and response models explicitly.
- Validate payload at boundary before domain logic.
- Convert transport model to domain model.
- Map domain exceptions to stable API error responses.
- Add tests for invalid input, timeout, dependency failure, and success.
- Migrate a module from untyped to typed contracts.
- Type public functions first.
- Introduce typed models for shared payloads.
- Replace implicit dictionary usage with explicit structures.
- Eliminate broad
Anypropagation. - Add type-check gating in verification flow.
- Stabilize async worker pipeline.
- Introduce bounded queue and worker semaphore.
- Define cancellation and shutdown sequence.
- Add timeout around external dependencies.
- Classify retryable vs permanent failures.
- Add tests for queue saturation and cancellation behavior.
- Refactor exception-heavy code path.
- Replace broad catches with specific exception types.
- Preserve operation context during wrapping.
- Separate user-facing messages from diagnostic details.
- Add explicit handling for expected recoverable failures.
Decision Tables
Use these quick choices during implementation.
- Sync vs async.
- Predominantly I/O with many concurrent waits: async workflow.
- Predominantly CPU-bound transformation: sync/process-oriented workflow.
- Mixed workload: isolate CPU hotspots from event loop paths.
- Data contract strategy.
- External payloads: validate at boundary.
- Internal domain data: typed models with invariant checks.
- Cross-module contracts: explicit typed interfaces.
- Error handling strategy.
- User-correctable input issue: validation error class.
- Transient dependency issue: retry-aware dependency error class.
- Invariant breach: fail fast path with strong diagnostics.
- Test strategy.
- Pure transforms: unit tests with edge cases.
- Adapter behavior: integration tests with boundary mocks or fixtures.
- Async orchestration: timeout/cancellation/boundedness tests.
Additional Resources
Load detailed references when needed.
references/asyncio-patterns.mdreferences/core-patterns.mdreferences/error-to-design-map.mdreferences/review-checklist.mdreferences/domain-web.mdreferences/domain-cli.mdreferences/domain-data.md
More from craftsman-labs/simpleagents
simpleagents-builder
This skill should be used when the user asks to create, improve, or validate YAML agent workflows, especially requests like "build an agent YAML", "design workflow YAML", "add routing in YAML", or "make interview/email workflow nodes and edges". Also use when the user describes a problem and wants a SimpleAgents solution built for them. The core vision is that every agentic SaaS is a config -- turn their problem into a YAML workflow.
9simpleagentsbuilder
This skill should be used when the user asks to create, improve, or validate YAML agent workflows, especially requests like "build an agent YAML", "design workflow YAML", "add routing in YAML", or "make interview/email workflow nodes and edges".
3skill-development
This skill provides guidance for creating effective skills for Claude Code plugins.
2typescript-javascript-coding-patterns
This skill should be used when the user asks to "implement TypeScript code", "debug JavaScript code", "refactor JS/TS code", "review TypeScript code", "fix async JavaScript issues", "improve TypeScript types", or "apply JavaScript best practices".
2code-reviewer
Use when completing tasks, implementing major features, or before merging to verify work meets requirements
1