简体   繁体   English

NaN 的 Pylint 冗余比较

[英]Pylint redundant comparison for NaN

Why does Pylint think this is a redundant comparison?为什么 Pylint 认为这是一个多余的比较? Is this not the fastest way to check for NaN?这不是检查 NaN 的最快方法吗?

Refactor: R0124重构:R0124
Redundant comparison - value_1 != value_1冗余比较 - value_1 != value_1
Redundant comparison - value_2 != value_2冗余比较 - value_2 != value_2

How else am I supposed to check if two values are equal including when they're nan?我还应该如何检查两个值是否相等,包括当它们为 nan 时?

NaN = float("NaN")

def compare(value_1, value_2):
    match_nan = value_1 != value_1
    print(match_nan and
          value_2 != value_2 or
          value_1 == value_2)

compare(1, 1)
compare(1, NaN)
compare(NaN, 1)
compare(NaN, NaN)

Output:输出:

True
False
False
True

Now, sure math.is_nan is a better solution if you're working with custom classes:现在,如果您正在使用自定义类,那么 math.is_nan 肯定是更好的解决方案:

from math import isnan

class NotEQ:
    def __eq__(self, other):
        return False
not_eq = NotEQ()
print(not_eq != not_eq)
print(isnan(not_eq))

Output:输出:

True
... TypeError: must be real number, not NotEQ

I'm writing a JSON patcher, and I don't think the normal behaviour is very useful when you want to be able to remove them from lists, or raise an error is two values aren't equal (but allowing NaN and NaN)我正在编写一个 JSON 修补程序,我认为当您希望能够从列表中删除它们时,正常行为不是很有用,或者如果两个值不相等则引发错误(但允许 NaN 和 NaN)

pylint throws this issue whenever you compare either a constant or a variable with itself.每当您将常量或变量与自身进行比较时,pylint 都会抛出此问题。 I case of a variable it compares the name (see _check_logical_tautology in the source ). I case of a variable it compares the name (see _check_logical_tautology in the source )。 So you could circumvent this by renaming one side of the comparison like this:因此,您可以通过像这样重命名比较的一侧来避免这种情况:

def compare(value_1, value_2):
    v_1 = value_1
    v_2 = value_2
    match_nan = v_1 != value_1
    print(match_nan and v_2 != value_2 or value_1 == value_2)

at least to get rid of the linting issue.至少要摆脱 linting 问题。 However I would also follow wjandrea's advice and go for How can I check for NaN values?不过,我也会听从 wjandrea 的建议并寻求How can I check for NaN values?

Use math.isnan(x) ;使用math.isnan(x) it's just as fast as x != x .它和x != x一样快。 The answer that says x != x is fastest is using a bad test (and I put a comment there to explain).x != x最快的答案是使用错误的测试(我在那里发表评论来解释)。 Here's a fixed version:这是一个固定版本:

In [1]: %%timeit x = float('nan')
   ...: x != x
   ...: 
   ...: 
36 ns ± 0.51 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)

In [2]: %%timeit x = float('nan'); from math import isnan
   ...: isnan(x)
   ...: 
   ...: 
35.8 ns ± 0.282 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)

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

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