python-best-practices-type-safety
Systematic resolution of pyright/mypy type errors with categorization and fix templates. Use when pyright fails, type errors are reported, adding type annotations, or enforcing type safety. Analyzes Python type errors, categorizes them (missing annotations, incorrect types, generic issues, Optional/None handling), and applies fix patterns. Works with .py files and pyright output.
What this skill does
# Debug Type Errors
## Purpose
Systematically diagnose and resolve Python type checking errors from pyright/mypy by categorizing error types and applying proven fix patterns.
## When to Use This Skill
Use when fixing type errors with "fix pyright errors", "resolve type mismatch", "add type annotations", or "handle Optional types".
Do NOT use for pytest configuration (use `pytest-configuration`), import validation (use `python-best-practices-fail-fast-imports`), or runtime errors (type checking is static).
## When to Use
Use this skill when:
- Pyright or mypy reports type errors in CI/CD or local checks
- Adding type annotations to untyped code
- Refactoring code and need to maintain type safety
- Debugging "Type X cannot be assigned to Y" errors
- Fixing Optional/None handling issues
- Resolving generic type argument errors
- Converting code to strict type checking mode
- Before committing changes (as part of quality gates)
## Table of Contents
### Core Sections
- [Purpose](#purpose) - Systematic type error diagnosis and resolution
- [Quick Start](#quick-start) - Fastest way to fix type errors with automation
- [Instructions](#instructions) - Complete implementation guide
- [Step 1: Run Type Checker and Capture Output](#step-1-run-type-checker-and-capture-output) - Pyright execution and error capture
- [Step 2: Categorize Errors](#step-2-categorize-errors) - 6 error categories with patterns
- [Step 3: Apply Fix Patterns](#step-3-apply-fix-patterns) - Category-specific fix templates
- [Step 4: Use MultiEdit for Batch Fixes](#step-4-use-multiedit-for-batch-fixes) - Token-efficient batch fixes
- [Step 5: Verify Fixes](#step-5-verify-fixes) - Post-fix validation
- [Examples](#examples) - Real-world error fixes
- [Example 1: Missing Return Type Annotation](#example-1-missing-return-type-annotation)
- [Example 2: Optional Parameter Handling](#example-2-optional-parameter-handling)
- [Example 3: Generic Type Arguments](#example-3-generic-type-arguments)
- [Common Error Patterns](#common-error-patterns) - Quick reference table
- [Project-Specific Rules](#project-specific-rules) - Strict type checking rules
- [Requirements](#requirements) - Python 3.11+, pyright, pyrightconfig.json
- [Automation Scripts](#automation-scripts) - Parser, annotation fixer, Optional handler
### Supporting Resources
- [scripts/README.md](./scripts/README.md) - Automation scripts and workflows
- [references/reference.md](./references/reference.md) - Complete error pattern catalog
- [CLAUDE.md](../../../CLAUDE.md) - Project type safety rules
- [../apply-code-template/references/code-templates.md](../../docs/code-templates.md) - Type-safe code templates
### Python Scripts
- [Parse Pyright Errors](./scripts/parse_pyright_errors.py) - Categorize and analyze pyright type checking errors
- [Fix Missing Annotations](./scripts/fix_missing_annotations.py) - Automatically add type hints to Python files
- [Fix Optional Handling](./scripts/fix_optional_handling.py) - Add None checks for Optional types
## Quick Start
**Using Automation Scripts (Recommended):**
```bash
# Parse and categorize errors
uv run pyright src/ | python .claude/skills/debug-type-errors/scripts/parse_pyright_errors.py
# Auto-fix missing annotations
python .claude/skills/debug-type-errors/scripts/fix_missing_annotations.py src/file.py --all --dry-run
# Auto-fix Optional handling
python .claude/skills/debug-type-errors/scripts/fix_optional_handling.py src/file.py --dry-run
```
**Manual Analysis:**
```bash
# Run pyright and capture errors
uv run pyright src/ > type_errors.txt
# Analyze errors by category
grep "is not assignable" type_errors.txt
grep "Cannot access member" type_errors.txt
grep "is not defined" type_errors.txt
# Fix using MultiEdit for multiple errors in same file
```
**See:** [scripts/README.md](./scripts/README.md) for complete automation workflow.
## Instructions
### Step 1: Run Type Checker and Capture Output
Run pyright with verbose output to get detailed error information:
```bash
# Project-wide check
uv run pyright src/ --verbose > type_errors.txt
# Specific file check
uv run pyright src/path/to/file.py --verbose
# Check with stats
uv run pyright src/ --stats
```
**Key flags:**
- `--verbose` - Shows full error context
- `--stats` - Displays error count by category
- No flags - Standard output (recommended for parsing)
### Step 2: Categorize Errors
Parse pyright output and group errors by category:
**Category 1: Missing Type Annotations**
```
error: Type of "variable" is unknown
error: Return type of function is unknown
error: Parameter "param" type is unknown
```
**Category 2: Type Mismatch (Assignment)**
```
error: Argument of type "X" cannot be assigned to parameter "Y"
error: Expression of type "X" cannot be assigned to declared type "Y"
error: Type "X" is not assignable to type "Y"
```
**Category 3: Optional/None Handling**
```
error: "None" is not assignable to "X"
error: Argument of type "X | None" cannot be assigned to parameter "X"
error: Object of type "None" cannot be used as iterable value
```
**Category 4: Generic Type Errors**
```
error: Type argument "X" is missing
error: Expected 1 type argument
error: Type "X[Y]" is incompatible with "X[Z]"
```
**Category 5: Attribute/Method Errors**
```
error: Cannot access member "X" for type "Y"
error: "X" is not a known member of "Y"
```
**Category 6: Import/Module Errors**
```
error: Import "X" could not be resolved
error: Stub file not found for "X"
```
### Step 3: Apply Fix Patterns
Use category-specific fix patterns (see `references/reference.md` for detailed examples):
**Pattern 1: Add Type Annotations**
```python
# Before
def process_data(data):
return data.strip()
# After
def process_data(data: str) -> str:
return data.strip()
```
**Pattern 2: Fix Type Mismatches**
```python
# Before
result: ServiceResult[bool] = service.get_data() # Returns ServiceResult[dict]
# After
result: ServiceResult[dict] = service.get_data()
```
**Pattern 3: Handle Optional Types**
```python
# Before
def get_value(config: Settings | None) -> str:
return config.value # Error: config might be None
# After
def get_value(config: Settings | None) -> str:
if not config:
raise ValueError("Config required")
return config.value
```
**Pattern 4: Fix Generic Types**
```python
# Before
items: list = [] # Missing type argument
# After
items: list[str] = []
```
### Step 4: Use MultiEdit for Batch Fixes
When fixing multiple errors in the same file, ALWAYS use MultiEdit:
```python
# ❌ WRONG - Sequential edits (wastes tokens)
Edit("file.py", old1, new1)
Edit("file.py", old2, new2)
# ✅ CORRECT - Single MultiEdit operation
MultiEdit("file.py", [
{"old_string": old1, "new_string": new1},
{"old_string": old2, "new_string": new2}
])
```
### Step 5: Verify Fixes
After applying fixes, verify the changes:
```bash
# Run pyright on specific file
uv run pyright src/path/to/file.py
# Run full type check
uv run pyright src/
# Run quality gates
./scripts/check_all.sh
```
## Examples
### Example 1: Missing Return Type Annotation
**Error:**
```
src/application/services/indexing_service.py:45:5 - error: Return type of "process" is unknown
```
**Fix:**
```python
# Before
def process(self, data: dict):
return ServiceResult.success(data)
# After
def process(self, data: dict) -> ServiceResult[dict]:
return ServiceResult.success(data)
```
### Example 2: Optional Parameter Handling
**Error:**
```
src/infrastructure/neo4j_repository.py:23:9 - error: Argument of type "Settings | None" cannot be assigned to parameter "settings" of type "Settings"
```
**Fix:**
```python
# Before
def __init__(self, settings: Settings | None = None):
self.settings = settings
# After
def __init__(self, settings: Settings):
if not settings:
raise ValueError("Settings required")
self.settings = settings
```
### Example 3: Generic Type Arguments
**Error:**
```
src/domain/entities/chunk.py:Related in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.