---
name: python3-development
description: 'The model must use this skill when : 1. working within any python project. 2. Python CLI applications with Typer and Rich are mentioned by the user. 2. tasked with Python script writing or editing. 3. building CI scripts or tools. 4. Creating portable Python scripts with stdlib only. 5. planning out a python package design. 6. running any python script or test. 7. writing tests (unit, integration, e2e, validation) for a python script, package, or application. Reviewing Python code against best practices or for code smells. 8. The python command fails to run or errors, or the python3 command shows errors. 9. pre-commit or linting errors occur in python files. 10. Writing or editing python code in a git repository.\nThis skill provides : 1. the users preferred workflow patterns for test-driven development, feature addition, refactoring, debugging, and code review using modern Python 3.11+ patterns (including PEP 723 inline metadata, native generics, and type-safe async processing). 2. References to favored modules. 3. Working pyproject.toml configurations. 4. Linting and formatting configuration and troubleshooting. 5. Resource files that provide solutions to known errors and linting issues. 6. Project layouts the user prefers.'
version: "1.1.0"
last_updated: "2025-11-04"
python_compatibility: "3.11+"
---
# Opinionated Python Development Skill
## Role Identification (Mandatory)
The model must identify its ROLE_TYPE and echo the following statement:
```text
My ROLE_TYPE is "". I follow instructions given to "the model" and "".
```
Where:
- `` is either "orchestrator" or "sub-agent" based on the ROLE_TYPE identification rules in CLAUDE.md
- `` is "orchestrator" if ROLE_TYPE is orchestrator, or "sub-agent" if ROLE_TYPE is sub-agent
**Example for orchestrator:**
```text
My ROLE_TYPE is "orchestrator". I follow instructions given to "the model" and "orchestrator".
```
**Example for sub-agent:**
```text
My ROLE_TYPE is "sub-agent". I follow instructions given to "the model" and "sub-agent".
```
---
Orchestration guide for Python development using specialized agents and modern Python 3.11-3.14 patterns.
## Skill Architecture
### Bundled Resources (Included in This Skill)
**Reference Documentation:**
- [User Project Conventions](./references/user-project-conventions.md) - Extracted conventions from user's production projects (MANDATORY for new projects)
- [Modern Python Modules](./references/modern-modules.md) - 50+ library guides with usage patterns and best practices
- [Tool & Library Registry](./references/tool-library-registry.md) - Development tools catalog for linting, testing, and build automation
- [API Reference](./references/api_reference.md) - API specifications and integration guides
- [Python Development Orchestration](./references/python-development-orchestration.md) - Detailed workflow patterns for TDD, feature addition, refactoring, and code review
**Command Templates and Guides** (`commands/`):
- Reference material for creating slash commands (NOT the actual slash commands)
- Command templates and patterns for development
- Testing and development workflow guides
- See [Commands README](./commands/README.md) for details
**Scripts and Assets:**
- Example scripts demonstrating patterns
- Configuration templates and boilerplate
### External Dependencies (Required - Not Bundled)
**Agents** (install to `~/.claude/agents/`):
- `@agent-python-cli-architect` - Python CLI development with Typer and Rich
- `@agent-python-pytest-architect` - Test suite creation and planning
- `@agent-python-code-reviewer` - Post-implementation code review
- `@agent-python-portable-script` - Standalone stdlib-only script creation
- `@agent-spec-architect` - Architecture design
- `@agent-spec-planner` - Task breakdown and planning
- `@agent-spec-analyst` - Requirements gathering
**Slash Commands** (install to `~/.claude/commands/`):
- `/modernpython` - Python 3.11+ pattern enforcement and legacy code detection
- `/shebangpython` - PEP 723 inline script metadata validation
**System Tools** (install via package manager or uv):
- `uv` - Python package and project manager (required)
- `ruff` - Linter and formatter
- `pyright` - Type checker (Microsoft)
- `mypy` - Static type checker
- `pytest` - Testing framework
- `pre-commit` - Git hook framework
- `mutmut` - Mutation testing (for critical code)
- `bandit` - Security scanner (for critical code)
**Installation Notes:**
- Agents and slash commands must be installed separately in their respective directories
- This skill provides orchestration guidance and references; agents perform actual implementation
- Use the `uv` skill for comprehensive uv documentation and package management guidance
## Core Concepts
### Python Development Standards
This skill provides orchestration patterns, modern Python 3.11+ standards, quality gates, and reference documentation for Python development.
**Commands** (external - in `~/.claude/commands/`):
- `/modernpython` - Validates Python 3.11+ patterns, identifies legacy code
- `/shebangpython` - Validates correct shebang for all Python scripts
- Note: This skill contains command templates in `commands/` directory, not the actual slash commands
**Reference Documentation**:
- Modern Python modules (50+ libraries)
- Tool and library registry with template variable system
- API specifications
- Working configurations for pyproject.toml, ruff, mypy, pytest
**Docstring Standard**: Google style (Args/Returns/Raises sections). See [User Project Conventions](./references/user-project-conventions.md) 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](./references/tool-library-registry.md#18-pyprojecttoml-template-variable-reference) for:
- Complete variable reference and sourcing methods
- Mandatory rules for file creation
- Validation and verification procedures
### Script Dependency Trade-offs
Understand the complexity vs portability trade-off when creating Python CLI scripts:
**Scripts with dependencies (Typer + Rich via PEP 723)**:
- ✅ **LESS development complexity** - Leverage well-tested libraries for argument parsing, formatting, validation
- ✅ **LESS code to write** - Typer handles CLI boilerplate, Rich handles output formatting
- ✅ **Better UX** - Colors, progress bars, structured output built-in
- ✅ **Just as simple to execute** - PEP 723 makes it a single-file executable; uv handles dependencies automatically
- ❌ **Requires network access** on first run (to fetch packages)
**stdlib-only scripts**:
- ❌ **MORE development complexity** - Build everything from scratch (manual argparse, manual tree formatting, manual color codes)
- ❌ **MORE code to write and test** - Everything must be implemented manually
- ❌ **Basic UX** - Limited formatting without external libraries
- ✅ **Maximum portability** - Runs on ANY Python installation without network access
- ✅ **Best for:** Air-gapped systems, restricted corporate environments, embedded systems
**Default recommendation:** Use Typer + Rich with PEP 723 unless you have specific portability requirements that prevent network access.
**See:**
- [Python Development Orchestration Guide](./references/python-development-orchestration.md) for detailed agent selection criteria
- [Typer and Rich CLI Examples](./assets/typer_examples/index.md) for Rich width handling solutions
### Rich Panel and Table Width Handling
**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**:
#### Solution 1: Plain Text (No Containers)
For plain text output that shouldn't wrap:
```python
from rich.console import Console
console = Console()
# URLs, paths, commands - never wrap
console.print(long_url, crop=False, overflow="ignore")
```
#### Solution 2: Rich Containers (Panel/Table)
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:
```python
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=9999)
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/](./assets/typer_examples/index.md) for complete working scripts:
- `console_no_wrap_example.py` - Plain text wrapping solutions
- `console_containers_no_wrap.py` - Panel/Table width handling with `get_rendered_width()`
### Rich Emoji Usage
**CRITICAL**: In Rich console output, always use Rich emoji tokens, never literal Unicode emojis.
**Never:**
- Literal Unicode: `✅ ❌ 🔍`
- Problems: Inconsistent rendering, markdown alignment issues, terminal font dependencies
**Always:**
- Rich emoji tokens: `:white_check_mark: :cross_mark: :magnifying_glass:`
- Benefits: Cross-platform compatibility, consistent rendering, markdown-safe
**Example:**
```python
from rich.console import Console
console = Console()
# ❌ Wrong - literal Unicode emojis
console.print("✅ Task completed")
console.print("❌ Task failed")
# ✅ 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")
```
**Why this matters:**
- Rich emoji tokens work consistently across all terminals and fonts
- Avoid markdown table alignment issues (emoji width calculation problems)
- Enable proper width measurement in `get_rendered_width()`
- Ensure cross-platform compatibility (Windows, Linux, macOS)
**See**: [Rich Emoji Documentation](https://rich.readthedocs.io/en/stable/appendix/colors.html#appendix-emoji) for complete emoji token reference.
### Python Exception Handling
Catch exceptions only when you have a specific recovery action. Let all other errors propagate to the caller.
**Pattern**:
```python
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](./references/exception-handling.md) for comprehensive patterns including Typer exception chain prevention.
## Agent Orchestration (Orchestrator Only)
### Delegation Pattern
The orchestrator must delegate Python development tasks to specialized agents rather than implementing directly.
**The orchestrator must**:
1. Read the complete orchestration guide before delegating tasks
2. Choose appropriate agents based on task requirements
3. Provide clear context: file paths, success criteria, scope boundaries
4. Chain agents for complex workflows (design → implement → test → review)
5. Validate outputs with quality gates
**The orchestrator must NOT**:
- Write Python implementation code directly
- Create tests directly
- Review code directly
- Make technical decisions that agents should determine
### Required Reading
**The orchestrator must read and understand the complete agent selection guide before delegating any Python development task:**
[Python Development Orchestration Guide](./references/python-development-orchestration.md)
This guide contains:
- Agent selection criteria and decision trees
- Workflow patterns (TDD, feature addition, code review, refactoring, debugging)
- Quality gates and validation requirements
- Delegation best practices
### Quick Reference Example
```text
User: "Build a CLI tool to process CSV files"
Orchestrator workflow:
1. Read orchestration guide for agent selection
2. Delegate to @agent-python-cli-architect
"Create CSV processing CLI with Typer+Rich progress bars"
3. Delegate to @agent-python-pytest-architect
"Create test suite for CSV processor"
4. Instruct agent to run: /shebangpython, /modernpython
5. Delegate to @agent-python-code-reviewer
"Review CSV processor implementation"
6. Validate: uv run pre-commit run --all-files && uv run pytest
```
## Command Usage
### /modernpython
**Purpose**: Comprehensive reference guide for Python 3.11+ patterns with official PEP citations
**When to use**:
- As reference guide when writing new code
- Learning modern Python 3.11-3.14 features and patterns
- Understanding official PEPs (585, 604, 695, etc.)
- Identifying legacy patterns to avoid
- Finding modern alternatives for old code
**Note**: This is a reference document to READ, not an automated validation tool. Use it to guide your implementation choices.
**Usage**:
```text
/modernpython
→ Loads comprehensive reference guide
→ Provides Python 3.11+ pattern examples
→ Includes PEP citations with WebFetch commands
→ Shows legacy patterns to avoid
→ Shows modern alternatives to use
→ Framework-specific guides (Typer, Rich, pytest)
```
**With file path argument**:
```text
/modernpython src/mymodule.py
→ Loads guide for reference while working on specified file
→ Use guide to manually identify and refactor legacy patterns
```
### /shebangpython
**Purpose**: Validate correct shebang for ALL Python scripts based on their dependencies and execution context
**When to use**:
- Creating any standalone executable Python script
- Validating script shebang correctness
- Ensuring scripts have proper execution configuration
**Required for**: ALL executable Python scripts (validates shebang matches script type)
**What it validates**:
- **Stdlib-only scripts**: `#!/usr/bin/env python3` (no PEP 723 needed - nothing to declare)
- **Scripts with dependencies**: `#!/usr/bin/env -S uv --quiet run --active --script` + PEP 723 metadata declaring those dependencies
- **Package executables**: `#!/usr/bin/env python3` (dependencies via package manager)
- **Library modules**: No shebang (not directly executable)
**See**: [PEP 723 Reference](./references/PEP723.md) for details on inline script metadata
**Pattern**:
```text
/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
```
## Core Workflows (Orchestrator Only)
The orchestrator must follow established workflow patterns for Python development tasks. See [Python Development Orchestration Guide](./references/python-development-orchestration.md) for complete details.
### Workflow Overview
1. **TDD (Test-Driven Development)**: Design → Write Tests → Implement → Review → Validate
2. **Feature Addition**: Requirements → Architecture → Plan → Implement → Test → Review
3. **Code Review**: Self-Review → Standards Check → Agent Review → Fix → Re-validate
4. **Refactoring**: Tests First → Refactor → Validate → Review
5. **Debugging**: Reproduce → Trace → Fix → Test → Review
Each workflow uses agent chaining with specific quality gates. See the orchestration guide for complete patterns, examples, and best practices.
## Linting Discovery Protocol
**The model MUST execute this discovery sequence before any linting or formatting operations**:
### Discovery Sequence
1. **Check for pre-commit configuration**:
```bash
# Verify .pre-commit-config.yaml exists
test -f .pre-commit-config.yaml && echo "pre-commit detected"
```
**If found**: Use `uv run pre-commit run --files ` for ALL quality checks
- This runs the complete toolchain configured in the project
- Includes formatting, linting, type checking, and custom validators
- Matches exactly what runs in CI and blocks merges
2. **Else check CI pipeline configuration**:
```bash
# 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
- Look for `ruff`, `mypy`, `basedpyright`, `pyright`, `bandit` invocations
- Note the exact commands and flags used
- Execute those specific commands to ensure CI compatibility
3. **Else fallback to tool detection**:
- Check `pyproject.toml` `[project.optional-dependencies]` or `[dependency-groups]` for dev tools
- Use discovered tools with standard configurations
### Format-First Workflow
**CRITICAL**: The model MUST always format before linting.
**Rationale**: 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**:
1. **Format**: `uv run ruff format ` or via pre-commit
2. **Lint**: `uv run ruff check ` or via pre-commit
3. **Type check**: Use project-configured type checker
4. **Test**: `uv run pytest`
**When using pre-commit**:
```bash
# Pre-commit runs tools in configured order (formatting first)
uv run pre-commit run --files
```
The `.pre-commit-config.yaml` already specifies correct ordering - trust it.
### Type Checker Discovery
**The model MUST detect which type checker the project uses**:
**Detection priority**:
1. Check `.pre-commit-config.yaml` for `basedpyright`, `pyright`, or `mypy` hooks
2. Check `pyproject.toml` for `[tool.basedpyright]`, `[tool.pyright]`, or `[tool.mypy]` sections
3. Check `.gitlab-ci.yml` or GitHub Actions for type checker invocations
**Common patterns**:
- **basedpyright**: GitLab projects (native GitLab reporting format)
- **pyright**: General TypeScript-style projects
- **mypy**: Python-first type checking
**Example detection**:
```bash
# Check pre-commit config
grep -E "basedpyright|pyright|mypy" .pre-commit-config.yaml
# Check pyproject.toml
grep -E "^\[tool\.(basedpyright|pyright|mypy)\]" pyproject.toml
```
**Never assume** - always detect from project configuration.
## Quality Gates
**The model MUST follow the Linting Discovery Protocol before executing quality gates.**
**Every Python task must pass**:
1. **Format-first**: `uv run ruff format ` (or via pre-commit)
2. **Linting**: `uv run ruff check ` (clean, after formatting)
3. **Type checking**: Use **detected type checker** (`basedpyright`, `pyright`, or `mypy`)
4. **Tests**: `uv run pytest` (>80% coverage)
5. **Modern patterns**: `/modernpython` (no legacy typing)
6. **Script compliance**: `/shebangpython` (for standalone scripts)
**Preferred execution method**:
```bash
# If .pre-commit-config.yaml exists (runs all checks in correct order):
uv run pre-commit run --files
# Else use individual tools in this exact sequence:
uv run ruff format # 1. Format first
uv run ruff check # 2. Lint after formatting
uv run # 3. Type check (basedpyright/pyright/mypy)
uv run pytest # 4. Test
```
**For critical code** (payments, auth, security):
- Coverage >95%
- Mutation testing: `uv run mutmut run` (>90% score)
- Security scan: `uv run bandit -r packages/`
**CI Compatibility Verification**:
After local quality gates pass, verify CI will accept the changes:
1. If `.gitlab-ci.yml` exists: Check for additional validators not in pre-commit
2. If `.github/workflows/*.yml` exists: Check for additional quality gates
3. Ensure all CI-required checks are executed locally before claiming task completion
## Standard Project Structure
All Python projects MUST use this directory layout:
```text
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**:
- Project name: `my-cli-tool` → Package directory: `packages/my_cli_tool/`
- Hyphens in project names become underscores in package directories
- The `packages/` directory distinguishes user code from external dependencies
**Hatchling Configuration**:
```toml
[tool.hatchling.build.targets.wheel]
packages = ["packages/package_name"]
```
This structure is consistent across all projects and enables clear separation of concerns.
## Integration
### External Reference Example
**Complete working example** (external): `~/.claude/agents/python-cli-demo.py`
This reference implementation demonstrates all recommended patterns:
- PEP 723 metadata with correct shebang
- Typer + Rich integration
- Modern Python 3.11+ (StrEnum, Protocol, TypeVar, Generics)
- Annotated syntax for CLI params
- Async processing
- Comprehensive docstrings
This file is not bundled with this skill and must be available in `~/.claude/agents/` separately. Use as reference when creating CLI tools.
### Using Asset Templates
When creating new Python projects, the model MUST copy standard configuration files from the skill's assets directory to ensure consistency with established conventions:
**Asset Directory Location**: `~/.claude/skills/python3-development/assets/`
**Available Templates**:
1. **version.py** - Dual-mode version management (hatch-vcs + importlib.metadata fallback)
```bash
cp ~/.claude/skills/python3-development/assets/version.py packages/{package_name}/version.py
```
2. **hatch_build.py** - Build hook for binary/asset handling (only if needed)
```bash
mkdir -p scripts/
cp ~/.claude/skills/python3-development/assets/hatch_build.py scripts/hatch_build.py
```
3. **.markdownlint.json** - Markdown linting configuration
```bash
cp ~/.claude/skills/python3-development/assets/.markdownlint.json .
```
4. **.pre-commit-config.yaml** - Standard pre-commit hooks
```bash
cp ~/.claude/skills/python3-development/assets/.pre-commit-config.yaml .
uv run pre-commit install
```
5. **.editorconfig** - Editor formatting settings
```bash
cp ~/.claude/skills/python3-development/assets/.editorconfig .
```
These templates implement the patterns documented in [User Project Conventions](./references/user-project-conventions.md) and ensure all projects follow the same standards for version management, linting, formatting, and build configuration.
## Common Anti-Patterns (Orchestrator Only)
❌ **Don't**: Write Python code as orchestrator → **Do**: Delegate to agents ❌ **Don't**: Skip validation steps → **Do**: Always complete workflow (implement → test → review → validate) ❌ **Don't**: Pre-decide technical implementations → **Do**: Let agents determine HOW based on requirements
For detailed anti-pattern examples and corrections, see [Anti-Patterns section](./references/python-development-orchestration.md#anti-patterns-to-avoid) in the orchestration guide.
## Detailed Documentation
### Reference Documentation
**Core Orchestration Guide**: [Python Development Orchestration](./references/python-development-orchestration.md) - Detailed workflow patterns for TDD, feature addition, refactoring, and code review with comprehensive agent coordination strategies
**PEP 723 Specification**: [PEP 723 - Inline Script Metadata](./references/PEP723.md) - User-friendly guide to PEP 723 inline script metadata with examples and migration patterns
**Exception Handling**: [Exception Handling in Python CLI Applications with Typer](./references/exception-handling.md) - 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](./assets/typer_examples/index.md) - 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](./references/modern-modules.md) - 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](./references/tool-library-registry.md) - Catalog of development tools, their purposes, and usage patterns for linting, testing, and build automation
**API Documentation**: [API Reference](./references/api_reference.md) - API specifications, integration guides, and programmatic interface documentation
#### Navigating Large References
To find specific modules in modern-modules.md:
```bash
grep -i "^### " references/modern-modules.md
```
To search for tools by category in tool-library-registry.md:
```bash
grep -A 5 "^## " references/tool-library-registry.md
```
To locate workflow patterns in python-development-orchestration.md:
```bash
grep -i "^## " references/python-development-orchestration.md
```
### External Commands
These slash commands are external dependencies installed in `~/.claude/commands/`:
- [/modernpython](~/.claude/commands/modernpython.md) - Python 3.11+ patterns and PEP references
- [/shebangpython](~/.claude/commands/shebangpython.md) - PEP 723 validation and shebang standards
## Summary
### Python Development Skill for All Roles
**For All Roles (Orchestrators and Agents)**:
- Modern Python 3.11+ standards and patterns
- Quality gates: ruff, pyright, mypy, pytest (>80% coverage)
- Command standards: /modernpython, /shebangpython
- Reference documentation for 50+ modern Python modules
- Tool and library registry
**For Orchestrators Only**:
1. Read the [orchestration guide](./references/python-development-orchestration.md) before delegating
2. Choose the right agent based on task requirements
3. Provide clear context: file paths, success criteria, scope boundaries
4. Chain agents for complex workflows (design → test → implement → review)
5. Instruct agents to validate with quality gates and commands
6. Enable uv skill for package management
**Orchestration = Coordination + Delegation + Validation**