简体   繁体   English

如何在不生成 PyLint 警告的情况下比较两个变量的类型?

[英]How do I compare the type of two variables without generating PyLint warnings?

Say I have two variables:假设我有两个变量:

a = 123
b = 234

I want to compare their type.我想比较他们的类型。 Clearly the obvious way is:显然,显而易见的方法是:

type(a) == type(b)

However, pylint gives me a warning, which I would like to avoid if possible:但是,pylint 给了我一个警告,如果可能的话,我想避免:

Using type() instead of isinstance() for a typecheck. (unidiomatic-typecheck)

(I believe this isn't specifically warning about my use.) (我相信这并不是特别警告我的使用。)

In the case of comparing two variable types, isinstance can't be used, I believe.在比较两个变量类型的情况下,我相信不能使用 isinstance 。

How do I compare the type of two variables without generating PyLint warnings?如何在不生成 PyLint 警告的情况下比较两个变量的类型?

Just turn off the pylint warning.只需关闭pylint警告。

On a single line, you can do that thusly:在一行中,您可以这样做:

types_match = type(a) is type(b) # pylint: disable=unidiomatic-typecheck

See https://pylint.readthedocs.io/en/latest/user_guide/message-control.html请参阅https://pylint.readthedocs.io/en/latest/user_guide/message-control.html

People get too hung up about linters.人们对短绒太着迷了。 It's like the PEP 8 style guide .这就像PEP 8 风格指南 They are guidelines, and you have to use your own judgment.它们是指导方针,您必须使用自己的判断。

If you need to know whether the type of something is the same as the type of something else, then absolutely the straightforward如果您需要知道某物的类型是否与其他事物的类型相同,那么绝对简单

type(a) == type(b)

is the most Pythonic way.是最 Pythonic 的方式。 It's not idiomatic Python to jump through crazy hoops to do simple things if you can avoid it.如果可以避免的话,跳出疯狂的圈子去做简单的事情并不是Python 惯用的做法。

All that said, it is usually not the case in Python that you really need to know whether the types of two things are exactly the same.尽管如此,在 Python 中通常情况并非如此,您真的需要知道两个事物的类型是否完全相同。 (See comments by BrenBarn and Chad S.) So the linter may be pointing to a larger "code smell" than just that one line which compares the two types. (请参阅 BrenBarn 和 Chad S 的评论。)因此,linter 可能指向更大的“代码气味”,而不仅仅是比较这两种类型的一行。

If you absolutely must compare if two of anything are of the exact same type, and you cannot use type() for some reason, the last resort may be:如果您绝对必须比较任何东西中的两个是否完全相同,并且由于某种原因不能使用type()则最后的手段可能是:

a.__class__ is b.__class__

Note also the limitation of this check on old-style classes.另请注意此检查对旧式类的限制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM