全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-19 6 分钟 ✍️ juanwangdev

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最主流,功能全面
pyrightMicrosoft,速度快
pytypeGoogle,推断能力强
pyreFacebook,适合大型项目
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 在开发流程中检测类型问题

📝 发现内容有误?点击此处直接编辑

← 上一篇 Python 类型别名
下一篇 → Python 类型注解语法
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库