Comparison of identical values¶
ID: py/comparison-of-identical-expressions Kind: problem 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
Click to see the query in the CodeQL repository
When two identical expressions are compared it is typically an indication of a mistake, since the Boolean value of the comparison will always be the same, unless the value is the floating point value
It is not good practice to compare a value with itself, as it makes the code hard to read and can hide errors with classes that do not correctly implement equality. If testing whether a floating-point value is not-a-number, then use
math.isnan(). If the value may be a complex number, then use
In this example
f == f is used to check for
float('nan'). This makes the code difficult to understand as the reader may not be immediately familiar with this pattern.
#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)
Python Language Reference: Comparisons.
Python Library Reference: math.isnan().
Python Library Reference: cmath.isnan().
Common Weakness Enumeration: CWE-570.
Common Weakness Enumeration: CWE-571.