Skip to content

Hoist Loop from If

Sourcery refactoring id: hoist-loop-from-if

Description:

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

Before:

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()

After:

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

Explanation:

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.