You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在无类型注解的情况下使用mypy检测类型错误?

如何用mypy检测无类型注解脚本中的类型错误

假设你有一段没加类型注解的Python脚本,里面藏着刻意设置的类型错误——就像下面这段代码,运行时会触发TypeError,但我们想在运行前用mypy提前揪出问题:

def foo(x, y):
    print(x[:y])
def main():
    foo('abcde', '2')
if __name__ == "__main__":
    main()

直接运行这段脚本会得到如下报错:

$ python3 untyped_test.py
Traceback (most recent call last):
  File "untyped_test.py", line 8, in <module>
    main()
  File "untyped_test.py", line 5, in main
    foo('abcde', '2')
  File "untyped_test.py", line 2, in foo
    print(x[:y])
TypeError: 切片索引必须为整数或有__index__方法

但默认情况下,mypy对无类型注解的函数是“宽容”的,直接跑mypy untyped_test.py不会给出任何错误提示。要让它检测这类无注解代码里的问题,你需要开启特定选项:

操作步骤

  • 先确保已安装mypy:pip install mypy
  • 运行mypy时加上--check-untyped-defs参数,这个参数会强制mypy检查所有无类型注解的函数:
    mypy --check-untyped-defs untyped_test.py
    

运行后,mypy会输出精准的错误提示:

untyped_test.py:5: error: Argument 2 to "foo" has incompatible type "str"; expected "int"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

这样就能在运行脚本前,提前发现把字符串'2'传给需要整数的切片索引这个问题了。

如果想要更全面的严格检查(比如推断更多潜在类型问题),可以直接使用--strict选项,它包含了--check-untyped-defs以及其他严格检查规则:

mypy --strict untyped_test.py

内容的提问来源于stack exchange,提问作者Tobias Hermann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:21:46