Comparison of constants¶
ID: py/comparison-of-constantsKind: problemSecurity severity: Severity: warningPrecision: very-highTags: - quality - maintainability - useless-code - external/cwe/cwe-570 - external/cwe/cwe-571Query suites: - python-security-and-quality.qls
Click to see the query in the CodeQL repository
When two constants are compared it is typically an indication of a mistake, since the Boolean value of the comparison will always be the same. In very old code this may be used to initializeTrue andFalse.
Recommendation¶
It is never good practice to compare a value with itself. If the constant behavior is indeed required, use the Boolean literalsTrue orFalse, rather than encoding them obscurely as1==1 or similar. If there is a mistake, ascertain the desired behavior and correct it.
Example¶
In this example, old code uses1==1 to initialize__builtins__.True. This code has been unnecessary on all versions of Python released since 2003 and can be deleted.
#Interoperate with very old versions of Python (pre 2.3)try:TrueexceptNameError:__builtins__.True=1==1
References¶
Python Language Reference:Comparisons.
Common Weakness Enumeration:CWE-570.
Common Weakness Enumeration:CWE-571.