Python 3.x 让mypy警告不同类型变量的相等性检查
mypy-strict允许以下最小示例,且没有任何错误:Python 3.x 让mypy警告不同类型变量的相等性检查,python-3.x,types,static-typing,mypy,Python 3.x,Types,Static Typing,Mypy,mypy-strict允许以下最小示例,且没有任何错误: a: int = 1 b: str = '1' if a == b: pass else: pass 如果a==b:line,是否有可能使其发出错误或至少警告?编辑:下面我的原始答案描述了如何通过编写自定义mypy插件来实现这一点 但是,现在可以通过-strict-equality标志直接执行此操作。请注意,在撰写本文时,默认情况下不会通过-strict标志启用此标志 例如,在上面的原始程序上运行mypy将产生以下错误
a: int = 1
b: str = '1'
if a == b:
pass
else:
pass
如果a==b:line,是否有可能使其发出错误或至少警告?编辑:下面我的原始答案描述了如何通过编写自定义mypy插件来实现这一点
但是,现在可以通过-strict-equality标志直接执行此操作。请注意,在撰写本文时,默认情况下不会通过-strict标志启用此标志
例如,在上面的原始程序上运行mypy将产生以下错误:
test.py:4: error: Non-overlapping equality check (left operand type: "int", right operand type: "str")
您可以在mypy命令行flags文档部分底部附近找到有关此标志的更多详细信息
这是可能的使用目前实验和未记录的插件API
简而言之,在项目中的某个位置添加以下文件:
from typing import Callable, Optional, Type
from mypy.plugin import MethodContext, Plugin
from mypy.meet import is_overlapping_types
class StrictEqualityPlugin(Plugin):
def get_method_hook(self, fullname: str) -> Optional[Callable[[MethodContext], Type]]:
if fullname.endswith('__eq__') or fullname.endswith('__ne__'):
return strict_check_callback
def strict_check_callback(ctx: MethodContext) -> Type:
if len(ctx.arg_types) == 1 and len(ctx.arg_types[0]) == 1:
# Note: Expressions of the form 'base_type == arg_type' get
# translated into `base_type.__eq__(arg_type)`.
base_type = ctx.type
arg_type = ctx.arg_types[0][0]
# Two types are overlapping if one of the types could potentially be the
# same as or a subtype of the other.
#
# If you want something even stricter, add `from mypy.sametypes import is_same_type`
# up at the top and call `is_same_type` instead of `is_overlapping_types`.
if not is_overlapping_types(base_type, arg_type):
ctx.api.msg.warn(
"The left and right operands have disjoint types ({} and {})".format(
ctx.api.msg.format(base_type),
ctx.api.msg.format(arg_type),
),
ctx.context)
return ctx.default_return_type
def plugin(mypy_version: str) -> Plugin:
return StrictEqualityPlugin
假设此文件的名称为strict\u equality\u plugins.py
然后,在项目的顶层创建一个文件。该文件至少应包含以下内容:
[mypy]
plugins = ./path/to/strict_equality_plugins.py
然后,在根项目中运行mypy将产生如下错误:
[mypy]
plugins = ./path/to/strict_equality_plugins.py
py:1:警告:左操作数和右操作数具有不相交的int和str类型
免责声明:mypy项目的插件API是高度实验性的——我不保证这个插件在mypy的未来版本中会继续工作,不做任何修改