python-best-practices-type-safety

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Debug 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
pytest-configuration
), import validation (use
python-best-practices-fail-fast-imports
), or runtime errors (type checking is static).
当你需要修复pyright错误、解决类型不匹配问题、添加类型注解或处理Optional类型时,可使用该技能。
请勿用于pytest配置(请使用
pytest-configuration
)、导入验证(请使用
python-best-practices-fail-fast-imports
)或运行时错误(类型检查是静态的)。

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)
在以下场景使用该技能:
  • Pyright或mypy在CI/CD或本地检查中报告类型错误
  • 为未添加类型注解的代码补充类型提示
  • 重构代码时需要维护类型安全
  • 调试“Type X cannot be assigned to Y”类型的错误
  • 修复Optional/None处理问题
  • 解决泛型类型参数错误
  • 将代码转换为严格类型检查模式
  • 提交更改前(作为质量门禁的一部分)

Table of Contents

目录

Core Sections

核心章节

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
undefined

Parse 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:**
```bash
python .claude/skills/debug-type-errors/scripts/fix_optional_handling.py src/file.py --dry-run

**手动分析:**
```bash

Run 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
undefined

Project-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 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"
解析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
references/reference.md
for detailed examples):
Pattern 1: Add Type Annotations
python
undefined
使用针对不同分类的修复模式(详见
references/reference.md
获取详细示例):
模式1:添加类型注解
python
undefined

Before

修复前

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**
```python
def process_data(data: str) -> str: return data.strip()

**模式2:修复类型不匹配**
```python

Before

修复前

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**
```python
result: ServiceResult[dict] = service.get_data()

**模式3:处理Optional类型**
```python

Before

修复前

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**
```python
def get_value(config: Settings | None) -> str: if not config: raise ValueError("Config required") return config.value

**模式4:修复泛型类型**
```python

Before

修复前

items: list = [] # Missing type argument
items: list = [] # 缺失类型参数

After

修复后

items: list[str] = []
undefined
items: list[str] = []
undefined

Step 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} ])
undefined
MultiEdit("file.py", [ {"old_string": old1, "new_string": new1}, {"old_string": old2, "new_string": new2} ])
undefined

Step 5: Verify Fixes

步骤5:验证修复结果

After applying fixes, verify the changes:
bash
undefined
应用修复后,验证更改是否有效:
bash
undefined

Run 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
undefined

Examples

示例

Example 1: Missing Return Type Annotation

示例1:缺失返回类型注解

Error:
src/application/services/indexing_service.py:45:5 - error: Return type of "process" is unknown
Fix:
python
undefined
错误信息:
src/application/services/indexing_service.py:45:5 - error: Return type of "process" is unknown
修复:
python
undefined

Before

修复前

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)
undefined
def process(self, data: dict) -> ServiceResult[dict]: return ServiceResult.success(data)
undefined

Example 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
undefined

Before

修复前

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
undefined
def init(self, settings: Settings): if not settings: raise ValueError("Settings required") self.settings = settings
undefined

Example 3: Generic Type Arguments

示例3:泛型类型参数

Error:
src/domain/entities/chunk.py:12:5 - error: Type argument for "list" is missing
Fix:
python
undefined
错误信息:
src/domain/entities/chunk.py:12:5 - error: Type argument for "list" is missing
修复:
python
undefined

Before

修复前

class Chunk: entities: list
class Chunk: entities: list

After

修复后

class Chunk: entities: list[str]
undefined
class Chunk: entities: list[str]
undefined

Common Error Patterns

常见错误模式

See
references/reference.md
for comprehensive error pattern catalog.
Quick Reference:
Error PatternFix Template
Type of "X" is unknown
Add type annotation
"X | None" cannot be assigned to "X"
Add None check with fail-fast
Type argument is missing
Add generic type parameter
Cannot access member "X"
Check type narrowing/guards
Import "X" could not be resolved
Install stub package or add type: ignore
详见
references/reference.md
获取完整的错误模式目录。
快速参考:
错误模式修复模板
Type of "X" is unknown
添加类型注解
"X | None" cannot be assigned to "X"
添加None检查并快速失败
Type argument is missing
添加泛型类型参数
Cannot access member "X"
检查类型收窄/守卫
Import "X" could not be resolved
安装存根包或添加type: ignore

Project-Specific Rules

项目特定规则

This project enforces strict type checking with the following rules:
  1. No Optional Config Parameters - Use
    Settings
    , not
    Settings | None
  2. Fail Fast on None - Check and raise ValueError immediately
  3. ServiceResult Returns - All service methods return
    ServiceResult[T]
  4. No Bare None Returns - Use
    ServiceResult.failure()
    instead
  5. Generic Types Required - Always specify type arguments:
    list[str]
    , not
    list
本项目强制执行严格类型检查,规则如下:
  1. 禁止可选配置参数 - 使用
    Settings
    ,而非
    Settings | None
  2. None值快速失败 - 立即检查并抛出ValueError
  3. ServiceResult返回值 - 所有服务方法返回
    ServiceResult[T]
  4. 禁止直接返回None - 使用
    ServiceResult.failure()
    替代
  5. 必须使用泛型类型 - 始终指定类型参数:
    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/
:
  1. 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
  2. fix_missing_annotations.py - Auto-add type hints
    • Infers return types from return statements
    • Detects ServiceResult[T] patterns
    • Suggests parameter types from usage
  3. 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/
目录下包含强大的自动化工具:
  1. parse_pyright_errors.py - 解析并分类pyright错误
    • 按错误类型分类(缺失注解、类型不匹配等)
    • 按文件和严重程度分组
    • 提供修复模板和快速解决方案
  2. fix_missing_annotations.py - 自动添加类型提示
    • 从返回语句推断返回类型
    • 识别ServiceResult[T]模式
    • 根据使用情况建议参数类型
  3. 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 - 类型安全代码模板