Skip to content

Swap If Else Branches

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

Sourcery refactoring id: swap-if-else-branches

Section titled “Sourcery refactoring id: swap-if-else-branches”

Swaps if and else branches of conditionals

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

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.