Consider using an `if` expressionPYL-R1706
An instance of the pre-Python 2.5 ternary syntax is being used. It is recommended to use an if
expression such as: foo if condition else bar
.
Using [condition] and [on_true] or [on_false]
may also give wrong results when on_true
has a false boolean value.
The inconsistency: Consider the following example:
def get_val(condition, fallback, on_truth=None):
if on_truth is None:
on_truth = []
return condition and on_truth or fallback
Here, if condition
is True
, the function is supposed to return the value on_truth
otherwise it will return the value fallback
.
This would work fine for calls where the on_truth
is not a falsey
value.
So, for a call: get_val(2>1, [1, 2, 3], [10, 20, 30])
, the output is as expected -> [10, 20, 30]
But, it would give the wrong result when on_truth
is falsey
value.
For the call: get_val(2>1, [1, 2, 3])
expected result is []
, but the function will return the fallback value [1, 2, 3]
.
This can be avoided by using if expression
.
Preferred:
def get_val(condition, fallback, on_truth=None):
if on_truth is None:
on_truth = []
return on_truth if condition else fallback
The if expression is also more readable and straight forward.