运行 mypy 与修复类型错误
配置 mypy、解读错误,并逐步为代码库添加类型。
运行 mypy 与修复类型错误 是 CoddyKit 上的免费 Python Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Python Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Python Academy 课程共包含 4 节课。
安装并运行 mypy
使用 pip 安装 mypy,然后在文件或包上运行它。它会报告类型错误,但不会执行您的代码。
# pip install mypy
# Check a single file:
# mypy script.py
# Check a package:
# mypy mypackage/
# Strict mode (recommended for new code):
# mypy --strict script.py您的第一个 mypy 错误
mypy 可以检测不兼容的类型、缺少的返回值,以及未添加注解的函数参数。
# script.py
def add(a, b): # mypy: Missing type annotation
return a + b
result: int = add("hello", 1) # str, not int
# mypy output:
# error: Returning Any from function declared to return "int"--strict 标志
--strict 会启用许多额外检查:缺少注解、Any 的使用、未添加类型信息的导入等。开始时不要启用它,之后再逐步添加。
# Most important strict flags individually:
# --disallow-untyped-defs
# --disallow-any-generics
# --warn-return-any
# --no-implicit-reexport
# Or all at once:
# mypy --strict mypackage/忽略错误
在行末添加 # type: ignore,即可抑制特定错误。请谨慎使用,并添加注释说明原因。
import third_party # type: ignore[import] # no stub available
x: int = get_dynamic_value() # type: ignore[assignment]mypy.ini / pyproject.toml 配置
将 mypy 设置存储在 mypy.ini 或 pyproject.toml 中,这样每次运行时就不必传递标志。
# mypy.ini
[mypy]
python_version = 3.11
strict = True
ignore_missing_imports = True
[mypy-third_party.*]
ignore_errors = True增量模式
mypy 会在多次运行之间缓存结果。它只会重新检查发生更改的文件,因此后续运行速度很快。
# First run:
# mypy mypackage/ — full analysis, ~5 s
# Second run (nothing changed):
# mypy mypackage/ — Success: no issues in 0 source files (0.3 s)常见错误:类型不兼容
最常见的错误是:分配或传递了类型错误的值。
# error: Incompatible types in assignment
# (expression has type "str", variable has type "int")
count: int = 0
count = "five" # error
# Fix:
count = 5常见错误:参数类型不匹配
向函数传递类型错误的参数。
def greet(name: str) -> str:
return f"Hello, {name}"
# error: Argument 1 to "greet" has incompatible type "int"
greet(42) # error
# Fix:
greet(str(42))常见错误:意外返回 None
函数声明返回非 None 值,但其中某条代码路径返回了 None。
# error: Missing return statement
def find(items: list[int], target: int) -> int:
for item in items:
if item == target:
return item
# Missing: no return if not found!
# Fix:
def find2(items: list[int], target: int) -> int | None:
for item in items:
if item == target:
return item
return None使用 isinstance 缩小类型范围
使用 isinstance 在分支内缩小 Union 类型的范围。mypy 能理解这一点,并相应地缩小类型范围。
def process(value: int | str) -> str:
if isinstance(value, int):
return str(value * 2) # mypy knows value is int here
return value.upper() # mypy knows value is str here使用 cast
typing.cast(Type, value) 告诉 mypy 将某个值视为给定类型,但不会产生运行时影响。仅在您确定自己的判断比 mypy 更准确时使用。
from typing import cast
def get_value() -> object:
return 42
result = cast(int, get_value()) # mypy treats result as int
print(result + 1) # 43快速检查
在一行中添加 # type: ignore 会产生什么效果?
回顾
运行 mypy script.py 检查类型。修复不兼容的赋值、参数不匹配和缺少返回值的问题。使用 isinstance 缩小联合类型,谨慎使用 # type: ignore,并在 mypy.ini 中配置 mypy。逐步启用 --strict。
常见问题解答
「运行 mypy 与修复类型错误」课时是免费的吗?
是的 — 「运行 mypy 与修复类型错误」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Python Academy 课程的其余内容,请升级到 CoddyKit PRO。 Python Academy 课程共包含 4 节课。
「运行 mypy 与修复类型错误」这节课中我会学到什么?
配置 mypy、解读错误,并逐步为代码库添加类型。 你通过在浏览器中直接运行的动手代码来练习 Python Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Python Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Python Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「运行 mypy 与修复类型错误」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Python Academy 课中编写并运行代码吗?
能。每节 Python Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 类型注解基础
- 复杂类型:List、Dict、Optional、Union
- TypeVar、泛型类与 Protocol
- 运行 mypy 与修复类型错误