栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Python

Python静态类型检查工具mypy

Python 更新时间:发布时间: 百科书网 趣学号

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
转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/1033019.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号