When a constant is used as a condition, either it has no effect on the execution flow and it can be removed, or some code will never be executed
and it is a bug.
This rule raises an issue when a constant expression is used as a condition in an if
, elif
, a conditional expression or
other boolean expressions.
Noncompliant Code Example
def func(param = None):
param = (1,)
if param: # Noncompliant. var is always set to (1,), the first branch of the if will always execute.
return sum(param)
else:
return None
var2 = 1 if func else 2 # Noncompliant. "func" will always be equivalent to True.
var3 = func and 1 else 2 # Noncompliant.
Compliant Solution
def func(param = None):
if param is None:
param = (1,)
if param:
return sum(param)
else:
return None
var2 = 1 if func() else 2
var3 = func() and 1 else 2
See