Python 类型检查工具
静态类型检查工具在运行前检测类型错误,提高代码可靠性。
mypy 安装与使用
Bash
pip install mypy
# 检查单个文件
mypy script.py
# 检查整个项目
mypy myapp/
# 详细输出
mypy --verbose script.py
mypy 输出示例
Python
# script.py
def greet(name: str) -> str:
return "Hello, " + name
greet(123) # 类型错误
运行 mypy script.py 输出:
Python
script.py:4: error: Argument 1 to "greet" has incompatible type "int"; expected "str"
常见类型错误
toml
# 类型不匹配
def add(a: int, b: int) -> int:
return a + b
add(1, "2") # error: 类型不兼容
# 返回类型错误
def get_value() -> int:
return "string" # error: 返回类型不匹配
# 缺少返回值
def maybe_return(x: int) -> int:
if x > 0:
return x
# error: 缺少返回值
# Optional 未处理 None
from typing import Optional
def get_name() -> Optional[str]:
return None
name = get_name()
print(name.upper()) # error: name 可能为 None
mypy 配置
Python
# pyproject.toml
[tool.mypy]
python_version = "3.10"
warn_return_any = true
warn_unused_ignores = true
disallow_untyped_defs = true
strict = true
# 排除模块
[[tool.mypy.overrides]]
module = "third_party.*"
ignore_errors = true
类型忽略
Bash
# 忽略单行类型检查
result = some_function() # type: ignore
# 忽略特定错误
result = some_function() # type: ignore[call-arg]
# 忽略整个函数
def legacy_function(x): # type: ignore
return x
严格模式
JSON
# 启用所有检查
mypy --strict script.py
# 配置严格模式
[tool.mypy]
strict = true
严格模式检查:
- 所有函数必须有类型注解
- 禁止使用 Any
- 检查所有 Optional 处理
VS Code 集成
Bash
// settings.json
{
"python.linting.mypyEnabled": true,
"python.linting.mypyArgs": [
"--strict"
]
}
PyCharm 集成
PyCharm 内置类型检查:
- 自动检测类型注解错误
- 实时显示类型不匹配警告
- Ctrl+Click 跳转到类型定义
其他类型检查工具
| 工具 | 特点 |
|---|---|
| mypy | 最主流,功能全面 |
| pyright | Microsoft,速度快 |
| pytype | Google,推断能力强 |
| pyre | Facebook,适合大型项目 |
Python
# pyright(VS Code 默认)
pip install pyright
pyright script.py
# pytype
pip install pytype
pytype script.py
类型检查与运行时
YAML
# 类型检查是静态的,不影响运行时
def greet(name: str) -> str:
return "Hello, " + name
# 类型检查报错,但运行时正常执行
greet(123) # 输出: Hello, 123
# 运行时类型验证需要手动检查
def greet_safe(name: str) -> str:
if not isinstance(name, str):
raise TypeError("name must be str")
return "Hello, " + name
CI/CD 集成
text
# GitHub Actions
- name: Type check
run: mypy --strict myapp/
# pre-commit
repos:
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.0.0
hooks:
- id: mypy
类型检查最佳实践
| 实践 | 建议 |
|---|---|
| 添加注解 | 所有公共函数添加类型注解 |
| 处理 None | 使用 Optional 时处理 None |
| 严格模式 | 新项目启用严格模式 |
| CI集成 | 在 CI 中运行类型检查 |
| 渐进应用 | 逐步添加类型注解 |
要点总结
- mypy 是最主流的静态类型检查工具
mypy script.py检查类型错误- 配置
pyproject.toml自定义检查规则 # type: ignore忽略特定类型检查--strict启用严格模式- IDE 集成提供实时类型检查
- 类型检查是静态的,不影响运行时
- 配合 CI/CD 在开发流程中检测类型问题
📝 发现内容有误?点击此处直接编辑