CodeQL 文档

冗余比较

ID: py/redundant-comparison
Kind: problem
Security severity: 
Severity: warning
Precision: high
Tags:
   - useless-code
   - external/cwe/cwe-561
   - external/cwe/cwe-570
   - external/cwe/cwe-571
Query suites:
   - python-security-and-quality.qls

点击查看 CodeQL 仓库中的查询

某些比较的结果有时可以从它们的上下文和其他比较的结果推断出来。这可能表明逻辑错误,并且如果例如循环条件从不改变其值,可能会导致死代码或无限循环。

建议

检查代码以查看逻辑是否正确,并考虑简化逻辑表达式。

示例

在以下(真实世界)示例中,测试 obj1 < obj2 被重复,因此第二个测试将始终为假,并且函数 _compare 将只返回 0-1

  class KeySorter:

      def __init__(self, obj):
          self.obj = obj

      def __lt__(self, other):
          return self._compare(self.obj, other.obj) < 0

      def _compare(self, obj1, obj2):
          if obj1 < obj2:
              return -1
          elif obj1 < obj2:
              return 1
          else:
              return 0

参考

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