Skip to content

Hoist Loop from If

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: hoist-loop-from-if

Section titled “Sourcery refactoring id: hoist-loop-from-if”

Moves loops that occur in all cases of an if statement outside of the conditional

def sing_song(self):
if style == 1:
while thing_true():
do_x()
elif style == 2:
while thing_true():
do_y()
elif style == 3:
while thing_true():
do_z()
def sing_song(self):
while thing_true():
if style == 1:
do_x()
elif style == 2:
do_y()
elif style == 3:
do_z()

Where the same for or while loop is defined in all branches of a conditional, the code can be considerably shortened and clarified by hoisting. By moving the loop outside, duplication is removed and the code becomes much clearer.