CodeQL documentation

Redundant comparison

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

Click to see the query in the CodeQL repository

The result of certain comparisons can sometimes be inferred from their context and the results of other comparisons. This can be an indication of faulty logic and may result in dead code or infinite loops if, for example, a loop condition never changes its value.


Inspect the code to check whether the logic is correct, and consider simplifying the logical expression.


In the following (real world) example the test obj1 < obj2 is repeated and thus the second test will always be false, and the function _compare will only ever return 0 or -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
              return 0