45 lines
1.1 KiB
Plaintext
45 lines
1.1 KiB
Plaintext
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
|
|
|
|
[source,text]
|
|
----
|
|
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
|
|
|
|
[source,text]
|
|
----
|
|
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
|
|
|
|
* https://www.python.org/dev/peps/pep-0285/[PEP 285 - Adding a bool type]
|
|
* https://docs.python.org/3/library/stdtypes.html#truth-value-testing[Python documentation - Truth Value Testing]
|
|
|