Constant in conditional expression or statementΒΆ
ID: py/constant-conditional-expression
Kind: problem
Severity: warning
Precision: very-high
Tags:
- maintainability
- 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
Using a constant value as a test in a conditional statement renders the statement pointless as only one branch will be run regardless of any other factors.
RecommendationΒΆ
If the conditional statement is required for debugging or similar then use a variable instead. Otherwise, remove the conditional statement and any associated dead code.
ExampleΒΆ
In the first example the if statement will always be executed and therefore can be removed. The contents of the statement should be kept though.
In the second example the statement l = 100 is never executed because 1 > 100 is always false. However, it is likely that the intention was l > 100 (the number β1β being misread as the letter βlβ) and that the test should be corrected, rather than deleted.
if True:
print "True is true!"
def limit(l):
if l < -100:
l = -100
if 1 > 100:
l = 100
return l
ReferencesΒΆ
Python: The If Statement.
Python: The While Statement.
Python: Literals (constant values).
Common Weakness Enumeration: CWE-561.
Common Weakness Enumeration: CWE-570.
Common Weakness Enumeration: CWE-571.