“E721:不比较类型,使用 isinstance()”错误

问题描述 投票:0回答:2

python PEP 8 linter 不喜欢这样:

assert type(a) == type(b)

它告诉我改用“isinstance()”。但要使用

isinstance
我必须做类似的事情

assert isinstance(a, type(b)) and isinstance(b, type(a))

这看起来更笨拙,我真的不明白这一点。

linter 是否以某种我看不到的方式变得聪明?或者我在某种程度上是明智的,linter 看不到?

python pep8
2个回答
12
投票

来自评论中添加的上下文:

根据我的程序逻辑,代码中的这一点应该有

type(a) == type(b)
,我只是想断言这一点以确保一切都运行顺利

在这种情况下,您应该忽略 linter,因为它没有建议任何对您有用的信息。 E721 旨在通过类型检查警告人们有关问题,例如:

if type(a) == A:
    ...

上面的示例可能会意外地破坏逻辑流程,因为忽略了

a
A
的子类实例的可能性。


0
投票

附注:

永远不要使用

isinstance()
来验证类型,一个例子是
True
False
被视为
int
的实例,因此如果您执行类似的操作来检查变量是否为 int:

>>> isinstance(True, int) # the result would be True
True

但另一方面:

>>> type(True) # the type of True is bool
<class 'bool'>
>>> type(True) is int # now the result makes sense
False
© www.soinside.com 2019 - 2024. All rights reserved.