Redundant comparison¶
ID: py/redundant-comparisonKind: problemSecurity severity: Severity: warningPrecision: highTags: - quality - maintainability - useless-code - external/cwe/cwe-561 - external/cwe/cwe-570 - external/cwe/cwe-571Query 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.
Recommendation¶
Inspect the code to check whether the logic is correct, and consider simplifying the logical expression.
Example¶
In the following (real world) example the testobj1<obj2 is repeated and thus the second test will always be false, and the function_compare will only ever return0 or-1.
classKeySorter:def__init__(self,obj):self.obj=objdef__lt__(self,other):returnself._compare(self.obj,other.obj)<0def_compare(self,obj1,obj2):ifobj1<obj2:return-1elifobj1<obj2:return1else:return0
References¶
Python Language Reference:Comparisons.
Common Weakness Enumeration:CWE-561.
Common Weakness Enumeration:CWE-570.
Common Weakness Enumeration:CWE-571.