本文目录导读:

我来详细说明如何在Python项目中集成Mypy进行类型检查。
安装Mypy
# 基础安装 pip install mypy # 如果需要特定Python版本支持 pip install mypy-ls # 用于编辑器集成
基本使用
命令行使用
# 检查单个文件 mypy script.py # 检查整个项目 mypy myproject/ # 检查特定包 mypy -p mypackage
配置文件配置
创建 mypy.ini 或 setup.cfg 或 pyproject.toml:
mypy.ini:
[mypy] python_version = 3.9 warn_return_any = True warn_unused_configs = True ignore_missing_imports = True strict_optional = True check_untyped_defs = True disallow_untyped_defs = False disallow_any_unimported = False [mypy.plugins.numpy.*] ignore_missing_imports = True
pyproject.toml (推荐):
[tool.mypy] python_version = "3.9" warn_return_any = true warn_unused_configs = true ignore_missing_imports = true strict_optional = true check_untyped_defs = true disallow_untyped_defs = false [[tool.mypy.overrides]] module = "numpy.*" ignore_missing_imports = true
编辑器集成
VS Code
在 settings.json 中配置:
{
"python.linting.mypyEnabled": true,
"python.linting.mypyArgs": [
"--ignore-missing-imports",
"--show-error-codes"
],
"python.linting.mypyPath": "mypy",
"python.linting.lintOnSave": true
}
或者安装 Pylance:
{
"python.analysis.typeCheckingMode": "basic" // basic, strict, off
}
Vim/Neovim (使用ALE插件)
" .vimrc
let g:ale_linters = {'python': ['mypy']}
let g:ale_fixers = {'python': ['black', 'isort']}
PyCharm
- 安装 Mypy 插件
- 设置 → 工具 → 外部工具 → 添加:
- Program:
mypy - Arguments:
$FilePath$ - Working directory:
$ProjectFileDir$
- Program:
CI/CD集成
GitHub Actions
name: Type Check
on: [push, pull_request]
jobs:
mypy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
- name: Install dependencies
run: |
pip install mypy
pip install -r requirements.txt
- name: Run mypy
run: mypy src/
pre-commit hooks
创建 .pre-commit-config.yaml:
repos:
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.4.1
hooks:
- id: mypy
args: [--ignore-missing-imports, --strict]
additional_dependencies: [types-requests]
类型检查实战
添加类型注解
from typing import List, Optional, Dict, Any
def process_data(data: List[str], config: Optional[Dict[str, Any]] = None) -> Dict[str, int]:
"""处理数据并返回结果"""
result = {}
if config is None:
config = {}
for item in data:
if item in config:
result[item] = len(item)
return result
# 使用泛型
from typing import TypeVar, Generic
T = TypeVar('T')
class Container(Generic[T]):
def __init__(self, item: T) -> None:
self._item = item
def get_item(self) -> T:
return self._item
常见类型检查策略
# 严格模式
# mypy: strict-optional
from typing import Optional, Union, List
def safe_divide(a: float, b: float) -> Optional[float]:
"""安全的除法运算"""
if b == 0:
return None
return a / b
# 渐进式类型检查
# 对旧项目逐步添加类型
# mypy: disallow_untyped_defs = False
def legacy_function(x, y): # 允许未类型化的函数
return x + y
高级配置
忽略特定错误
# 行内忽略 x: Any = 1 # type: ignore y: int = process() # type: ignore[assignment] # 文件级别忽略 # mypy: ignore_errors
自定义插件
# mypy_plugin.py
from mypy.plugin import Plugin, FunctionContext
from mypy.types import Type
class MyPlugin(Plugin):
def get_function_hook(self, fullname: str):
if fullname == 'mymodule.validate':
return self.validate_hook
return None
def validate_hook(self, ctx: FunctionContext) -> Type:
# 自定义类型检查逻辑
return ctx.default_return_type
def plugin(version: str):
return MyPlugin
最佳实践
-
从宽松开始,逐步严格
# 开始 mypy --ignore-missing-imports . # 逐步增加严格性 mypy --strict .
-
使用类型存根文件
# 创建 .pyi 文件 # mymodule.pyi def process(x: int) -> str: ...
-
处理第三方库
pip install types-requests types-PyYAML types-python-dateutil
-
配合其他工具
# 在 CI 中组合使用 black --check . isort --check-only . mypy . pytest
常见问题解决
# 忽略 missing import mypy --ignore-missing-imports . # 检查特定模块 mypy -m mymodule # 生成类型检查报告 mypy --html-report ./mypy_report . # 增量检查(提高性能) mypy --cache-dir .mypy_cache --incremental .
Mypy 集成可以显著提高代码质量,建议在项目初期就引入,并配合 CI/CD 流程自动执行类型检查。