Swap If Expression¶
Sourcery refactoring id: swap-if-expression
¶
Description¶
Swap the if
and else
branches of an if-expression to remove a negation
Before¶
my_hat = hats.bowler if not weather.is_sunny() else hats.baseball_cap
After¶
my_hat = hats.baseball_cap if weather.is_sunny() else hats.bowler
Explanation¶
Negated conditions are more difficult to read than positive ones, so it is best
to avoid them where we can. By swapping the if
and else
conditions around we
can invert the condition and make it positive.