python-best-practices-type-safety
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDebug Type Errors
排查类型错误
Purpose
用途
Systematically diagnose and resolve Python type checking errors from pyright/mypy by categorizing error types and applying proven fix patterns.
通过对错误类型进行分类并应用成熟的修复模式,系统性诊断和解决pyright/mypy报告的Python类型检查错误。
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 ), import validation (use ), or runtime errors (type checking is static).
pytest-configurationpython-best-practices-fail-fast-imports当你需要修复pyright错误、解决类型不匹配问题、添加类型注解或处理Optional类型时,可使用该技能。
请勿用于pytest配置(请使用)、导入验证(请使用)或运行时错误(类型检查是静态的)。
pytest-configurationpython-best-practices-fail-fast-importsWhen 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)
在以下场景使用该技能:
- Pyright或mypy在CI/CD或本地检查中报告类型错误
- 为未添加类型注解的代码补充类型提示
- 重构代码时需要维护类型安全
- 调试“Type X cannot be assigned to Y”类型的错误
- 修复Optional/None处理问题
- 解决泛型类型参数错误
- 将代码转换为严格类型检查模式
- 提交更改前(作为质量门禁的一部分)
Table of Contents
目录
Core Sections
核心章节
- Purpose - Systematic type error diagnosis and resolution
- Quick Start - Fastest way to fix type errors with automation
- Instructions - Complete implementation guide
- Step 1: Run Type Checker and Capture Output - Pyright execution and error capture
- Step 2: Categorize Errors - 6 error categories with patterns
- Step 3: Apply Fix Patterns - Category-specific fix templates
- Step 4: Use MultiEdit for Batch Fixes - Token-efficient batch fixes
- Step 5: Verify Fixes - Post-fix validation
- Examples - Real-world error fixes
- Common Error Patterns - Quick reference table
- Project-Specific Rules - Strict type checking rules
- Requirements - Python 3.11+, pyright, pyrightconfig.json
- Automation Scripts - Parser, annotation fixer, Optional handler
- 用途 - 系统性类型错误诊断与解决
- 快速开始 - 使用自动化工具快速修复类型错误
- 操作指南 - 完整的实施步骤
- 步骤1:运行类型检查器并捕获输出 - Pyright执行与错误捕获
- 步骤2:错误分类 - 6类错误及对应模式
- 步骤3:应用修复模式 - 针对不同分类的修复模板
- 步骤4:使用MultiEdit批量修复 - 高效批量修复错误
- 步骤5:验证修复结果 - 修复后的验证操作
- 示例 - 真实场景的错误修复案例
- 常见错误模式 - 快速参考表
- 项目特定规则 - 严格类型检查规则
- 环境要求 - Python 3.11+, pyright, pyrightconfig.json
- 自动化脚本 - 解析器、注解修复工具、Optional处理工具
Supporting Resources
支持资源
- scripts/README.md - Automation scripts and workflows
- references/reference.md - Complete error pattern catalog
- CLAUDE.md - Project type safety rules
- ../apply-code-template/references/code-templates.md - Type-safe code templates
- scripts/README.md - 自动化脚本与工作流
- references/reference.md - 完整的错误模式目录
- CLAUDE.md - 项目类型安全规则
- ../apply-code-template/references/code-templates.md - 类型安全代码模板
Python Scripts
Python脚本
- Parse Pyright Errors - Categorize and analyze pyright type checking errors
- Fix Missing Annotations - Automatically add type hints to Python files
- Fix Optional Handling - Add None checks for Optional types
- Parse Pyright Errors - 分类并分析pyright类型检查错误
- Fix Missing Annotations - 自动为Python文件添加类型提示
- Fix Optional Handling - 为Optional类型添加None检查
Quick Start
快速开始
Using Automation Scripts (Recommended):
bash
undefined使用自动化脚本(推荐):
bash
undefinedParse and categorize errors
解析并分类错误
uv run pyright src/ | python .claude/skills/debug-type-errors/scripts/parse_pyright_errors.py
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
python .claude/skills/debug-type-errors/scripts/fix_missing_annotations.py src/file.py --all --dry-run
Auto-fix Optional handling
自动修复Optional类型处理
python .claude/skills/debug-type-errors/scripts/fix_optional_handling.py src/file.py --dry-run
**Manual Analysis:**
```bashpython .claude/skills/debug-type-errors/scripts/fix_optional_handling.py src/file.py --dry-run
**手动分析:**
```bashRun pyright and capture errors
运行pyright并捕获错误
uv run pyright src/ > type_errors.txt
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
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
使用MultiEdit修复同一文件中的多个错误
**See:** [scripts/README.md](./scripts/README.md) for complete automation workflow.
**参考:** [scripts/README.md](./scripts/README.md) 获取完整的自动化工作流。Instructions
操作指南
Step 1: Run Type Checker and Capture Output
步骤1:运行类型检查器并捕获输出
Run pyright with verbose output to get detailed error information:
bash
undefined运行带详细输出的pyright命令以获取完整的错误信息:
bash
undefinedProject-wide check
全项目检查
uv run pyright src/ --verbose > type_errors.txt
uv run pyright src/ --verbose > type_errors.txt
Specific file check
单个文件检查
uv run pyright src/path/to/file.py --verbose
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)uv run pyright src/ --stats
**关键参数:**
- `--verbose` - 显示完整的错误上下文
- `--stats` - 按分类显示错误数量
- 无参数 - 标准输出(推荐用于解析)Step 2: Categorize Errors
步骤2:错误分类
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 unknownCategory 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 valueCategory 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"解析pyright输出并按类别分组错误:
分类1:缺失类型注解
error: Type of "variable" is unknown
error: Return type of function is unknown
error: Parameter "param" type is unknown分类2:类型不匹配(赋值)
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"分类3:Optional/None处理
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分类4:泛型类型错误
error: Type argument "X" is missing
error: Expected 1 type argument
error: Type "X[Y]" is incompatible with "X[Z]"分类5:属性/方法错误
error: Cannot access member "X" for type "Y"
error: "X" is not a known member of "Y"分类6:导入/模块错误
error: Import "X" could not be resolved
error: Stub file not found for "X"Step 3: Apply Fix Patterns
步骤3:应用修复模式
Use category-specific fix patterns (see for detailed examples):
references/reference.mdPattern 1: Add Type Annotations
python
undefined使用针对不同分类的修复模式(详见 获取详细示例):
references/reference.md模式1:添加类型注解
python
undefinedBefore
修复前
def process_data(data):
return data.strip()
def process_data(data):
return data.strip()
After
修复后
def process_data(data: str) -> str:
return data.strip()
**Pattern 2: Fix Type Mismatches**
```pythondef process_data(data: str) -> str:
return data.strip()
**模式2:修复类型不匹配**
```pythonBefore
修复前
result: ServiceResult[bool] = service.get_data() # Returns ServiceResult[dict]
result: ServiceResult[bool] = service.get_data() # 返回ServiceResult[dict]
After
修复后
result: ServiceResult[dict] = service.get_data()
**Pattern 3: Handle Optional Types**
```pythonresult: ServiceResult[dict] = service.get_data()
**模式3:处理Optional类型**
```pythonBefore
修复前
def get_value(config: Settings | None) -> str:
return config.value # Error: config might be None
def get_value(config: Settings | None) -> str:
return config.value # 错误:config可能为None
After
修复后
def get_value(config: Settings | None) -> str:
if not config:
raise ValueError("Config required")
return config.value
**Pattern 4: Fix Generic Types**
```pythondef get_value(config: Settings | None) -> str:
if not config:
raise ValueError("Config required")
return config.value
**模式4:修复泛型类型**
```pythonBefore
修复前
items: list = [] # Missing type argument
items: list = [] # 缺失类型参数
After
修复后
items: list[str] = []
undefineditems: list[str] = []
undefinedStep 4: Use MultiEdit for Batch Fixes
步骤4:使用MultiEdit批量修复
When fixing multiple errors in the same file, ALWAYS use MultiEdit:
python
undefined当需要修复同一文件中的多个错误时,请务必使用MultiEdit:
python
undefined❌ WRONG - Sequential edits (wastes tokens)
❌ 错误方式 - 逐个编辑(浪费令牌)
Edit("file.py", old1, new1)
Edit("file.py", old2, new2)
Edit("file.py", old1, new1)
Edit("file.py", old2, new2)
✅ CORRECT - Single MultiEdit operation
✅ 正确方式 - 单次MultiEdit操作
MultiEdit("file.py", [
{"old_string": old1, "new_string": new1},
{"old_string": old2, "new_string": new2}
])
undefinedMultiEdit("file.py", [
{"old_string": old1, "new_string": new1},
{"old_string": old2, "new_string": new2}
])
undefinedStep 5: Verify Fixes
步骤5:验证修复结果
After applying fixes, verify the changes:
bash
undefined应用修复后,验证更改是否有效:
bash
undefinedRun pyright on specific file
检查单个文件
uv run pyright src/path/to/file.py
uv run pyright src/path/to/file.py
Run full type check
全项目类型检查
uv run pyright src/
uv run pyright src/
Run quality gates
运行质量门禁检查
./scripts/check_all.sh
undefined./scripts/check_all.sh
undefinedExamples
示例
Example 1: Missing Return Type Annotation
示例1:缺失返回类型注解
Error:
src/application/services/indexing_service.py:45:5 - error: Return type of "process" is unknownFix:
python
undefined错误信息:
src/application/services/indexing_service.py:45:5 - error: Return type of "process" is unknown修复:
python
undefinedBefore
修复前
def process(self, data: dict):
return ServiceResult.success(data)
def process(self, data: dict):
return ServiceResult.success(data)
After
修复后
def process(self, data: dict) -> ServiceResult[dict]:
return ServiceResult.success(data)
undefineddef process(self, data: dict) -> ServiceResult[dict]:
return ServiceResult.success(data)
undefinedExample 2: Optional Parameter Handling
示例2:Optional参数处理
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
undefined错误信息:
src/infrastructure/neo4j_repository.py:23:9 - error: Argument of type "Settings | None" cannot be assigned to parameter "settings" of type "Settings"修复:
python
undefinedBefore
修复前
def init(self, settings: Settings | None = None):
self.settings = settings
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
undefineddef init(self, settings: Settings):
if not settings:
raise ValueError("Settings required")
self.settings = settings
undefinedExample 3: Generic Type Arguments
示例3:泛型类型参数
Error:
src/domain/entities/chunk.py:12:5 - error: Type argument for "list" is missingFix:
python
undefined错误信息:
src/domain/entities/chunk.py:12:5 - error: Type argument for "list" is missing修复:
python
undefinedBefore
修复前
class Chunk:
entities: list
class Chunk:
entities: list
After
修复后
class Chunk:
entities: list[str]
undefinedclass Chunk:
entities: list[str]
undefinedCommon Error Patterns
常见错误模式
See for comprehensive error pattern catalog.
references/reference.mdQuick Reference:
| Error Pattern | Fix Template |
|---|---|
| Add type annotation |
| Add None check with fail-fast |
| Add generic type parameter |
| Check type narrowing/guards |
| Install stub package or add type: ignore |
详见 获取完整的错误模式目录。
references/reference.md快速参考:
| 错误模式 | 修复模板 |
|---|---|
| 添加类型注解 |
| 添加None检查并快速失败 |
| 添加泛型类型参数 |
| 检查类型收窄/守卫 |
| 安装存根包或添加type: ignore |
Project-Specific Rules
项目特定规则
This project enforces strict type checking with the following rules:
- No Optional Config Parameters - Use , not
SettingsSettings | None - Fail Fast on None - Check and raise ValueError immediately
- ServiceResult Returns - All service methods return
ServiceResult[T] - No Bare None Returns - Use instead
ServiceResult.failure() - Generic Types Required - Always specify type arguments: , not
list[str]list
本项目强制执行严格类型检查,规则如下:
- 禁止可选配置参数 - 使用,而非
SettingsSettings | None - None值快速失败 - 立即检查并抛出ValueError
- ServiceResult返回值 - 所有服务方法返回
ServiceResult[T] - 禁止直接返回None - 使用替代
ServiceResult.failure() - 必须使用泛型类型 - 始终指定类型参数:,而非
list[str]list
Requirements
环境要求
- Python 3.11+
- pyright (installed via uv):
uv pip install pyright - Project type checking config in
pyrightconfig.json
- Python 3.11+
- pyright(通过uv安装):
uv pip install pyright - 项目类型检查配置文件
pyrightconfig.json
Automation Scripts
自动化脚本
This skill includes powerful automation utilities in :
scripts/-
parse_pyright_errors.py - Parse and categorize pyright errors
- Categorizes errors by type (missing annotations, type mismatch, etc.)
- Groups by file and severity
- Provides fix templates and quick wins
-
fix_missing_annotations.py - Auto-add type hints
- Infers return types from return statements
- Detects ServiceResult[T] patterns
- Suggests parameter types from usage
-
fix_optional_handling.py - Fix Optional/None handling
- Detects Optional parameters without None checks
- Adds fail-fast validation
- Follows project pattern:
if not param: raise ValueError()
See: scripts/README.md for usage examples and workflow integration.
该技能在目录下包含强大的自动化工具:
scripts/-
parse_pyright_errors.py - 解析并分类pyright错误
- 按错误类型分类(缺失注解、类型不匹配等)
- 按文件和严重程度分组
- 提供修复模板和快速解决方案
-
fix_missing_annotations.py - 自动添加类型提示
- 从返回语句推断返回类型
- 识别ServiceResult[T]模式
- 根据使用情况建议参数类型
-
fix_optional_handling.py - 修复Optional/None处理问题
- 检测未添加None检查的Optional参数
- 添加快速失败验证
- 遵循项目模式:
if not param: raise ValueError()
参考: scripts/README.md 获取使用示例和工作流集成方法。
See Also
相关链接
- scripts/README.md - Automation scripts and workflows
- references/reference.md - Complete error pattern catalog
- CLAUDE.md - Project type safety rules
- ../apply-code-template/references/code-templates.md - Type-safe code templates
- scripts/README.md - 自动化脚本与工作流
- references/reference.md - 完整的错误模式目录
- CLAUDE.md - 项目类型安全规则
- ../apply-code-template/references/code-templates.md - 类型安全代码模板