返回专栏
专栏 ·

8.2 静态类型检查实战:在 CI/CD 中集成 mypy 或 pyright 提前消灭潜在 Bug

作者: 九路 共 12 章 · 48 小节

欢迎回到 HelloWorld 技术社区(www.helloworld.net) 《Python 现代开发实战》专栏。

Python 解释器本身在运行时完全忽略类型注解,真正的威力来自静态类型检查器——mypy 或微软出品的极速引擎 pyright。它们能在代码还没运行之前,就揪出 NoneType has no attribute ... 这类占线上报错 60% 以上的低级失误。

在 pyproject.toml 中加入严格检查配置:

[tool.mypy]
python_version = "3.13"
strict = true
warn_return_any = true
disallow_untyped_defs = true

在 CI 流水线或本地提交前一键扫描:

uv add --dev mypy
uv run mypy src/

💬 HelloWorld 社区实战打卡

在开启 mypy --strict 后,如果你写 user = find_user_by_id(1, cache) 然后直接调用 user.upper(),为什么 mypy 会报错拒绝通过?应该如何通过类型收窄(Type Narrowing)修复?带 #Python专栏打卡 解答!