Skip to content

Swap If Else Branches

Sourcery refactoring id: swap-if-else-branches

Description:

Swaps if and else branches of conditionals

Before:

if location == OUTSIDE:
    pass
else:
    take_off_hat()

After:

if location != OUTSIDE:
    take_off_hat()
else:
    pass

Explanation:

One pattern we sometimes see is a conditional where nothing happens in the main body, and all of the action is in the else clause.

In this case we can make the code shorter and more concise by swapping the main body and the else around. We have to make sure to invert the conditional, then the logic from the else clause moves into the main body.

We then have an else clause which does nothing, so we can remove it.

if location != OUTSIDE:
    take_off_hat()

This is easier to read, and the intent of the conditional is clearer. When reading the code I don't have to mentally invert it to understand it, since that has been done for me.

Sourcery will also make this change if the else can be dropped since the body of the if is a guard condition.

Back to top