rspec/rules/S5797/rule.adoc

47 lines
1.2 KiB
Plaintext

== Why is this an issue?
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
----
== Resources
* 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]