CodeQL 文档

相同值的比较

ID: py/comparison-of-identical-expressions
Kind: problem
Security severity: 
Severity: warning
Precision: very-high
Tags:
   - reliability
   - correctness
   - readability
   - convention
   - external/cwe/cwe-570
   - external/cwe/cwe-571
Query suites:
   - python-security-and-quality.qls

点击查看 CodeQL 代码库中的查询

当比较两个相同的表达式时,通常表明存在错误,因为比较的布尔值始终相同,除非该值为浮点数 float('nan')

建议

将值与其自身进行比较的做法并不理想,因为它会使代码难以阅读,并且可能会隐藏对未正确实现相等性的类的错误。如果要测试浮点数是否为 NaN,请使用 math.isnan()。如果该值可能是复数,请改用 cmath.isnan()

示例

在本例中,f == f 用于检查 float('nan')。这会使代码难以理解,因为读者可能不会立即熟悉这种模式。


#Using 'x == x' to check that 'x' is not a float('nan').
def is_normal(f):
    return not cmath.isinf(f) and f == f

#Improved version; intention is explicit.
def is_normal(f):
    return not cmath.isinf(f) and not cmath.isnan(f)

参考资料

  • ©GitHub, Inc.
  • 条款
  • 隐私