Python 3.11+ development with CLI apps (Typer/Rich), testing (pytest), linting (ruff/mypy), and TDD workflows. Use when building Python CLIs, writing tests, fixing linting errors, configuring pyproject.toml, creating portable scripts, or reviewing Python code for best practices.
The model must identify its ROLE_TYPE and echo the following statement:
My ROLE_TYPE is "<the role type>". I follow instructions given to "the model" and "<role name>".
Where:
<the role type> is either "orchestrator" or "sub-agent" based on the ROLE_TYPE identification rules in CLAUDE.md<role name> is "orchestrator" if ROLE_TYPE is orchestrator, or "sub-agent" if ROLE_TYPE is sub-agentExample for orchestrator:
My ROLE_TYPE is "orchestrator". I follow instructions given to "the model" and "orchestrator".
Example for sub-agent:
My ROLE_TYPE is "sub-agent". I follow instructions given to "the model" and "sub-agent".
<section ROLE_TYPE="orchestrator">
</section>
<section ROLE_TYPE="orchestrator">
</section>
<section ROLE_TYPE="orchestrator">
</section>
<section ROLE_TYPE="orchestrator">
</section>Orchestration guide for Python development using specialized agents and modern Python 3.11-3.14 patterns.
Reference Documentation:
Command Templates and Guides (commands/):
../../commands/ directory for detailsScripts and Assets:
This plugin bundles the core agents and workflows needed for Python 3.11+ development and SAM-style execution:
./plugins/python3-development/agents/): python-cli-architect, python-pytest-architect, python-cli-design-spec, swarm-task-planner, plus SAM workflow agents (feature research/analysis/verification).modernpython, shebangpython, and the SAM workflow skills (add-new-feature, implement-feature, start-task, complete-implementation).System Tools (install via package manager or uv):
uv - Python package and project manager (required)ruff - Linter and formatterpyright - Type checker (Microsoft)mypy - Static type checkerpytest - Testing frameworkpre-commit - Git hook frameworkmutmut - Mutation testing (for critical code)bandit - Security scanner (for critical code)Installation Notes:
uv skill for comprehensive uv documentation and package management guidanceThis skill provides orchestration patterns, modern Python 3.11+ standards, quality gates, and reference documentation for Python development.
Note on command templates:
This plugin includes command templates under ./commands/ as reference material. For actual invocation, prefer skills (e.g., modernpython, shebangpython).
Reference Documentation:
Docstring Standard: Google style (Args/Returns/Raises sections). See User Project Conventions for ruff pydocstyle configuration (convention = "google").
CRITICAL: Pyproject.toml Template Variables:
All pyproject.toml examples use explicit template variables (e.g., {{project_name_from_directory_or_git_remote}}) instead of generic placeholders. The model MUST replace ALL template variables with actual values before creating files. See Tool & Library Registry sections 18-19 for:
Understand the complexity vs portability trade-off when creating Python CLI scripts:
Scripts with dependencies (Typer + Rich via PEP 723):
stdlib-only scripts:
Default recommendation: Use Typer + Rich with PEP 723 unless you have specific portability requirements that prevent network access.
See:
Common Problem: Rich containers (Panel, Table) wrap content at 80 characters in CI/non-TTY environments, breaking URLs, commands, and structured output.
Two Solutions Depending on Context:
For plain text output that shouldn't wrap:
from rich.console import Console
console = Console()
# URLs, paths, commands - never wrap
console.print(long_url, crop=False, overflow="ignore")
For Panel and Table that contain long content, crop=False alone doesn't work because containers calculate their own internal layout. Use get_rendered_width() helper with different patterns for Panel vs Table:
from rich.console import Console, RenderableType
from rich.measure import Measurement
from rich.panel import Panel
from rich.table import Table
def get_rendered_width(renderable: RenderableType) -> int:
"""Get actual rendered width of Rich renderable.
Handles color codes, Unicode, styling, padding, borders.
Works with Panel, Table, or any Rich container.
"""
temp_console = Console(width=99999)
measurement = Measurement.get(temp_console, temp_console.options, renderable)
return int(measurement.maximum)
console = Console()
# Panel: Set Console width (Panel fills Console width)
panel = Panel(long_content)
panel_width = get_rendered_width(panel)
console.width = panel_width # Set Console width, NOT panel.width
console.print(panel, crop=False, overflow="ignore", no_wrap=True, soft_wrap=True)
# Table: Set Table width (Table controls its own width)
table = Table()
table.add_column("Type", style="cyan", no_wrap=True)
table.add_column("Value", style="green", no_wrap=True)
table.add_row("Data", long_content)
table.width = get_rendered_width(table) # Set Table width
console.print(table, crop=False, overflow="ignore", no_wrap=True, soft_wrap=True)
Executable Examples: See ./assets/typer_examples/ for complete working scripts:
console_no_wrap_example.py - Plain text wrapping solutionsconsole_containers_no_wrap.py - Panel/Table width handling with get_rendered_width()Instruction: In Rich console output, always use Rich emoji tokens instead of literal Unicode emojis.
Use Rich emoji tokens: :white_check_mark: :cross_mark: :magnifying_glass:
Why: Cross-platform compatibility, consistent rendering, markdown-safe alignment
Example:
from rich.console import Console
console = Console()
# Correct - Rich emoji tokens
console.print(":white_check_mark: Task completed")
console.print(":cross_mark: Task failed")
console.print(":sparkles: New feature")
console.print(":rocket: Performance improvement")
Benefits:
get_rendered_width()See: Rich Emoji Documentation for complete emoji token reference.
Catch exceptions only when you have a specific recovery action. Let all other errors propagate to the caller.
Reason: Fail-fast principle surfaces issues early rather than hiding them behind generic error messages.
Pattern:
def get_user(id):
return db.query(User, id) # Errors surface naturally
def get_user_with_handling(id):
try:
return db.query(User, id)
except ConnectionError:
logger.warning("DB unavailable, using cache")
return cache.get(f"user:{id}") # Specific recovery action
When adding try/except, answer: "What specific error do I expect, and what is my recovery action?"
See: Exception Handling in Python CLI Applications for comprehensive patterns including Typer exception chain prevention.
REQUIREMENT: All Python code MUST be comprehensively typed using Python 3.11+ native type hints.
Python Version: Python 3.11+ is required unless explicitly documented otherwise. Older versions are rare, documented exceptions.
The model MUST read the official mypy documentation examples before implementing type patterns.
For comprehensive type safety guidance including Generics, Protocols, TypedDict, Type Narrowing, attrs/dataclasses/pydantic comparison, and mypy configuration, see Type Safety with Mypy Reference.
Before using the Task tool for ANY Python development delegation, the orchestrator MUST complete this checklist. This is NOT optional. Skipping this protocol leads to agent context exhaustion, architectural mistakes, and failed delegations.
| Step | Action | Verification |
|---|---|---|
| 1 | Read orchestration guide | Read("${CLAUDE_PLUGIN_ROOT}/skills/python3-development/references/python-development-orchestration.md") |
| 2 | Identify workflow pattern | Which pattern applies? (TDD / Feature Addition / Refactoring / Debugging / Code Review) |
| 3 | Plan agent chain | List ALL agents needed in sequence (never single-agent for complex tasks) |
| 4 | Define scope boundaries | What is IN scope? What is OUT of scope for each agent? |
| 5 | Set success criteria | What specific, measurable outcomes define completion? |
BLOCKING RULE: If you cannot answer steps 2-5 from memory, you have NOT read the orchestration guide. Go back to step 1.
Important distinction: Step 1 reads the orchestration meta-guide to understand HOW to coordinate agents. This is the only file the orchestrator reads before delegating. Do NOT read task codebase files, source code, or configuration before delegating — pass file paths to agents. Agents discover and verify file contents themselves as part of their Chain of Verification.
Problem observed: Orchestrators skip reading the guide, send one massive task to a single agent, the agent runs out of context, makes architectural mistakes, and user must intervene.
Solution: Reading the guide FIRST reveals:
The orchestrator must state which workflow pattern they are using before the first Task tool invocation:
"I have read the orchestration guide. Using [WORKFLOW PATTERN] with agents: [AGENT1] → [AGENT2] → [AGENT3]"
If you find yourself about to delegate without this statement, STOP and read the guide first.
Anti-pattern: Reading files, running commands, or exploring the codebase to "understand the problem" before delegating, then summarizing findings for the agent.
Why this is wrong:
Agents perform Chain of Verification (CoVe): Agents follow the Scientific Execution Protocol. They read files, form hypotheses, and verify their understanding against actual source code. Your pre-gathered summary bypasses their verification process.
Shallow read vs. focused discovery: You read without knowing what the agent needs. The agent reads with focused intent—they know what they're building and what details matter.
Stale/incomplete data treated as fact: Your summary may be incomplete or misunderstood. The agent may incorrectly treat your pre-gathered observations as verified facts rather than re-verifying.
Context waste: Pre-gathering uses YOUR context, then the agent re-reads anyway. Double the context cost, half the accuracy.
The agent has read access to everything. Let them discover and verify.
What TO provide:
The orchestrator delegates Python development tasks to specialized agents rather than implementing directly.
Reason: Agents have focused expertise and appropriate tool access for their specific domains.
The orchestrator follows this pattern:
The orchestrator delegates rather than implements:
| Task Type | Delegation Target |
|---|---|
| Python code | @python3-development:python-cli-architect |
| Test creation | @python3-development:python-pytest-architect |
| Code review | @python3-development:python-code-reviewer |
| Stdlib-only script | /python3-development:stdlib-scripting |
| Architecture | @python3-development:python-cli-design-spec |
| Task breakdown | @python3-development:swarm-task-planner |
| Requirements | @spec-analyst |
Reason for delegation table: Clear mapping prevents orchestrator from implementing when it should coordinate.
The orchestrator MUST read this guide BEFORE any delegation. Not reading it is the #1 cause of failed Python development tasks.
This guide contains:
User: "Build a CLI tool to process CSV files"
Orchestrator workflow:
0. Read("${CLAUDE_PLUGIN_ROOT}/skills/python3-development/references/python-development-orchestration.md")
"I have read the orchestration guide. Using FEATURE ADDITION workflow with agents:
@python3-development:python-cli-architect → @python3-development:python-pytest-architect → @python3-development:python-code-reviewer"
1. Delegate to @python3-development:python-cli-architect
"Create a CSV processing CLI with Typer+Rich progress bars.
Success: CLI accepts CSV file input, displays progress bar, outputs results.
Follow existing project structure and conventions."
2. Delegate to @python3-development:python-pytest-architect
"Create test suite for the CSV processor CLI.
Success: Tests cover all CLI commands, edge cases, and error paths. Coverage >80%."
3. Instruct agent to run: /python3-development:shebangpython, /python3-development:modernpython
4. Delegate to @python3-development:python-code-reviewer (FOCUSED SCOPE: review only)
"Review CSV processor implementation for patterns and quality."
5. Validate: Code quality checks per holistic-linting skill, then uv run pytest
Notice: Each delegation has FOCUSED SCOPE. The orchestrator read the guide FIRST and stated the workflow pattern BEFORE any Task tool usage.
Purpose: Comprehensive reference guide for Python 3.11+ patterns with official PEP citations
When to use:
Note: This is a reference document to READ, not an automated validation tool. Use it to guide your implementation choices.
Usage:
/python3-development:modernpython
→ Loads comprehensive reference guide
→ Provides Python 3.11+ pattern examples
→ Includes PEP citations with research tool guidance (prefer MCP tools: Ref/exa over WebFetch)
→ Shows legacy patterns to avoid
→ Shows modern alternatives to use
→ Framework-specific guides (Typer, Rich, pytest)
Research tool preference for PEP documentation:
1. mcp__Ref__ref_search_documentation(query="PEP {number} Python enhancement proposal")
2. mcp__exa__get_code_context_exa(query="PEP {number} implementation examples")
3. WebFetch as fallback
> [Web resource access, definitive guide for getting accurate data for high quality results](./references/accessing_online_resources.md)
With file path argument:
/python3-development:modernpython src/mymodule.py
→ Loads guide for reference while working on specified file
→ Use guide to manually identify and refactor legacy patterns
Purpose: Validate correct shebang for ALL Python scripts based on their dependencies and execution context
When to use:
Required for: ALL executable Python scripts (validates shebang matches script type)
What it validates:
#!/usr/bin/env python3 (no PEP 723 needed - nothing to declare)#!/usr/bin/env -S uv --quiet run --active --script + PEP 723 metadata declaring those dependencies#!/usr/bin/env python3 (dependencies via package manager)See: PEP 723 Reference for details on inline script metadata
Pattern:
/python3-development:shebangpython scripts/deploy.py
→ Analyzes imports to determine dependency type
→ **Corrects shebang** to match script type (edits file if wrong)
→ **Adds PEP 723 metadata** if external dependencies detected (edits file)
→ **Removes PEP 723 metadata** if stdlib-only (edits file)
→ Sets execute bit if needed
→ Provides detailed verification report
The orchestrator follows established workflow patterns for Python development tasks. See Python Development Orchestration Guide for complete details.
Every task MUST begin with discovery and planning before implementation.
Why: Skipping discovery leads to rework, missed patterns, and integration failures. The planning phase identifies context, patterns, and dependencies that inform implementation.
Phase 1: Discovery (before any implementation)
Phase 2: Planning (before writing code)
swarm-task-planner agent for complex tasksPhase 3: Implementation
Phase 4: Verification
uv run pytestpython-code-reviewer agentEach workflow uses agent chaining with specific quality gates. See the orchestration guide for complete patterns, examples, and best practices.
The model executes this discovery sequence before any linting or formatting operations:
Reason: Projects use different tool configurations. Discovery ensures compatibility with project standards and CI pipelines.
Check for git hook tool configuration:
# Verify .pre-commit-config.yaml exists
test -f .pre-commit-config.yaml && echo "git hook config detected"
If found: Detect and run the correct git hook tool:
# Detect tool (outputs 'prek' or 'pre-commit')
uv run python -c "print(open('.git/hooks/pre-commit').readlines()[1].split()[4].rstrip(':') if __import__('pathlib').Path('.git/hooks/pre-commit').exists() else 'prek')"
# Or use the holistic-linting detection script if available
uv run holistic-linting/scripts/detect_hook_tool.py run --files <files>
Detection logic: reads .git/hooks/pre-commit line 2, token 5 identifies the tool. Defaults to prek.
Note: prek is a Rust-based drop-in replacement for pre-commit. Both tools use the same .pre-commit-config.yaml and have identical CLI interfaces.
Use detected tool with: uv run <detected-tool> run --files <files> for ALL quality checks
Else check CI pipeline configuration:
# Check for GitLab CI or GitHub Actions
test -f .gitlab-ci.yml || find .github/workflows -name "*.yml" 2>/dev/null
If found: Read the CI config to identify required linting tools and their exact commands
ruff, mypy, basedpyright, pyright, bandit invocationsElse fallback to tool detection:
pyproject.toml [project.optional-dependencies] or [dependency-groups] for dev toolsThe model always formats before linting.
Reason: Formatting operations (like ruff format) automatically fix many linting issues (whitespace, line length, quote styles). Running linting before formatting wastes context and creates false positives.
Mandatory sequence:
uv run ruff format <files> or via git hook tool (pre-commit/prek)uv run ruff check <files> or via git hook tooluv run pytestWhen using git hook tool (pre-commit or prek):
# Detect which tool is installed, then run it
# Tool runs hooks in configured order (formatting first)
uv run <detected-tool> run --files <files>
The .pre-commit-config.yaml already specifies correct ordering - trust it.
The model detects which type checker the project uses:
Reason: Projects standardize on different type checkers (basedpyright, pyright, mypy). Using the wrong one produces incompatible results.
Detection priority:
.pre-commit-config.yaml for basedpyright, pyright, or mypy hookspyproject.toml for [tool.basedpyright], [tool.pyright], or [tool.mypy] sections.gitlab-ci.yml or GitHub Actions for type checker invocationsCommon patterns:
Example detection:
# Check .pre-commit-config.yaml (works with both pre-commit and prek)
grep -E "basedpyright|pyright|mypy" .pre-commit-config.yaml
# Check pyproject.toml
grep -E "^\[tool\.(basedpyright|pyright|mypy)\]" pyproject.toml
Always detect from project configuration rather than assuming.
The model follows the Linting Discovery Protocol before executing quality gates.
Every Python task must pass:
uv run ruff format <files> (or via git hook tool)uv run ruff check <files> (clean, after formatting)basedpyright, pyright, or mypy)uv run pytest (>80% coverage)/python3-development:modernpython (no legacy typing)/python3-development:shebangpython (for standalone scripts)Preferred execution method:
# If .pre-commit-config.yaml exists (runs all checks in correct order):
# First detect which tool is installed (pre-commit or prek), then:
uv run <detected-tool> run --files <changed_files>
# Else use individual tools in this exact sequence:
uv run ruff format <files> # 1. Format first
uv run ruff check <files> # 2. Lint after formatting
uv run <detected-type-checker> <files> # 3. Type check (basedpyright/pyright/mypy)
uv run pytest # 4. Test
For critical code (payments, auth, security):
uv run mutmut run (>90% score)uv run bandit -r packages/CI Compatibility Verification:
After local quality gates pass, verify CI will accept the changes:
.gitlab-ci.yml exists: Check for additional validators not in pre-commit.github/workflows/*.yml exists: Check for additional quality gatesThe model MUST NOT ignore or bypass linting errors UNLESS the code falls into one of these categories:
Acceptable Exceptions (OK to ignore linting):
Unacceptable Exceptions (MUST fix or escalate):
If NONE of the above conditions apply, the model MUST:
# type: ignore, # noqa, or similar suppressions without explicit user approvalRule Codes That MUST Always Be Fixed (never suppress):
These rule codes indicate real code quality issues that must be resolved at root cause:
except Exception with specific exception typesPer-File Exceptions in pyproject.toml (acceptable):
The following rules may be configured as per-file ignores in pyproject.toml [tool.ruff.lint.per-file-ignores]:
**/scripts/**: T201 (print), S (security), DOC, ANN401, PLR0911, PLR0917, PLC0415**/tests/**: S, D, E501, ANN, DOC, PLC, SLF, PLR, EXE, N, T**/assets/**: PLC0415, DOCtypings/**: N, ANN, AThese configurations allow relaxed checking in appropriate contexts without inline suppressions.
Touched Files Must Be Clean:
When files are modified, moved, or renamed, all linting issues in those files MUST be resolved before committing. Touching a file means taking responsibility for its quality.
All Python projects use this directory layout:
Reason: Consistent structure enables reliable automation and clear separation between user code and dependencies.
project-root/
├── pyproject.toml
├── packages/
│ └── package_name/ # Package code (hyphens in project name → underscores)
│ ├── __init__.py
│ └── ...
├── tests/
├── scripts/
├── sessions/ # Optional: cc-sessions framework
└── README.md
Package Directory Naming:
my-cli-tool → Package directory: packages/my_cli_tool/packages/ directory distinguishes user code from external dependenciesHatchling Configuration:
[tool.hatchling.build.targets.wheel]
packages = ["packages/package_name"]
This structure is consistent across all projects and enables clear separation of concerns.
Complete working example (bundled): python-cli-demo.py
This reference implementation demonstrates all recommended patterns:
This file is bundled with this plugin to keep the workflow self-contained. Use it as reference when creating CLI tools.
When creating new Python projects, copy standard configuration files from the skill's assets directory to ensure consistency with established conventions:
Reason: Templates implement proven patterns and save setup time.
Asset Directory Location (in plugin): ./assets/
Available Templates:
version.py - Dual-mode version management (hatch-vcs + importlib.metadata fallback)
cp "${CLAUDE_PLUGIN_ROOT}/skills/python3-development/assets/version.py" "packages/{package_name}/version.py"
hatch_build.py - Build hook for binary/asset handling (only if needed)
mkdir -p scripts/
cp "${CLAUDE_PLUGIN_ROOT}/skills/python3-development/assets/hatch_build.py" "scripts/hatch_build.py"
.markdownlint.json - Markdown linting configuration
cp "${CLAUDE_PLUGIN_ROOT}/skills/python3-development/assets/.markdownlint.json" "."
.pre-commit-config.yaml - Standard git hooks configuration
cp "${CLAUDE_PLUGIN_ROOT}/skills/python3-development/assets/example.pre-commit-config.yaml" ".pre-commit-config.yaml"
# Install hooks using pre-commit or prek (whichever is available)
# Both tools use the same configuration file and have identical interfaces
uv run pre-commit install # or: uv run prek install
.editorconfig - Editor formatting settings
cp "${CLAUDE_PLUGIN_ROOT}/skills/python3-development/assets/.editorconfig" "."
These templates implement the patterns documented in User Project Conventions and ensure all projects follow the same standards for version management, linting, formatting, and build configuration.
Delegation Pattern:
| Instead of | Use this pattern |
|---|---|
| Delegating without reading guide | ALWAYS read orchestration guide first, state workflow pattern |
| Sending one massive task to agent | Break into focused delegations with bounded scope |
| Writing Python code directly | Delegate to @python3-development:python-cli-architect with clear requirements |
| Skipping validation steps | Complete workflow: implement → test → review → validate |
| Pre-deciding technical implementations | Let agents determine HOW based on requirements |
| Implementing and testing in same step | Chain agents: @python3-development:python-cli-architect → @python3-development:python-pytest-architect |
Reason: Orchestrators coordinate workflows. Agents have specialized expertise and focused tool access for implementation.
For detailed pattern examples and corrections, see Anti-Patterns section in the orchestration guide.
Core Orchestration Guide: Python Development Orchestration - Detailed workflow patterns for TDD, feature addition, refactoring, and code review with comprehensive agent coordination strategies
PEP 723 Specification: PEP 723 - Inline Script Metadata - User-friendly guide to PEP 723 inline script metadata with examples and migration patterns
Exception Handling: Exception Handling in Python CLI Applications with Typer - Critical guidance on preventing exception chain explosion in Typer applications with correct patterns for graceful error handling
Typer and Rich Examples: Typer and Rich CLI Examples - Executable examples demonstrating solutions to common problems with Rich Console text wrapping in CI/non-TTY environments and Panel/Table content wrapping
Module Reference: Modern Python Modules - Comprehensive guide to 50+ modern Python libraries with deep-dive documentation for each module including usage patterns and best practices
Tool Registry: Tool & Library Registry - Catalog of development tools, their purposes, and usage patterns for linting, testing, and build automation
API Documentation: API Reference - API specifications, integration guides, and programmatic interface documentation
To find specific modules in modern-modules.md:
grep -i "^### " references/modern-modules.md
To search for tools by category in tool-library-registry.md:
grep -A 5 "^## " references/tool-library-registry.md
To locate workflow patterns in python-development-orchestration.md:
grep -i "^## " references/python-development-orchestration.md
These skills are bundled with this plugin and available as slash commands:
For All Roles (Orchestrators and Agents):
For Orchestrators Only:
Orchestration = Coordination + Delegation + Validation