当前位置: 首页 > 工具软件 > mypy > 使用案例 >

Python静态类型检查工具mypy

黄扬
2023-12-01

mypy工具可以用于检查不符合Python类型注解的语句。

例如,如果直接跑test.py:

# test.py
from typing import List

a: List[int] = []
a.append('1')
print(a)

输出:

['1']

虽然‘1’不是int,但是也不会报错,因为typing的注解只是一种提示。那typing只相当于注释吗?其实不是,可以用静态类型检查工具来发现这种错误,例如mypy。

mypy使用前需要用pip安装:

pip3 install mypy

使用方法是mypy+需要检查的.py文件:

mypy test.py

输出:

test.py:12: error: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
Found 1 error in 1 file (checked 1 source file)

如果想忽略这个错误,可以在对应行的后面加上# type:ignore

# test.py
from typing import List

a: List[int] = []
a.append('1')  # type:ignore
print(a)

再用mypy检查,输出:

Success: no issues found in 1 source file

但是这一行就不能有其它注释,否则会失效,例如下面两种写法:

a.append('1')  # test # type: ignore

a.append('1')  # test type: ignore
 类似资料: