Skip to content

Hoist statement out of loop

Sourcery refactoring id: hoist-statement-from-loop

Description:

Moves statements that are constant across all cases of a loop outside of the loop

Before:

for building in buildings:
    city = 'London'
    addresses.append(building.street_address, city)

After:

city = 'London'
for building in buildings:
    addresses.append(building.street_address, city)

Explanation:

Another type of hoisting is pulling invariant statements out of loops. If a statement just sets up some variables for use in the loop, it doesn't need to be inside it. Loops are inherently complex, so making them shorter and easier to understand should be on your mind while writing them.

In this example the city variable gets assigned inside the loop, but it is only read and not altered.

It's therefore safe to hoist it out, and this makes it clearer that the same city value will apply to every building.

This also improves performance - any statement in a loop is going to be executed every time the loop runs. The time spent on these multiple executions is being wasted, since it only needs to be executed once. This saving can be significant if the statements involve calls to databases or other time-consuming tasks.

Back to top