Hoist Statement from Loop
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-statement-from-loop
Section titled “Sourcery refactoring id: hoist-statement-from-loop”Description:
Section titled “Description:”Moves statements that are constant across all cases of a loop outside of the loop
Before:
Section titled “Before:”for building in buildings: city = "London" addresses.append(building.street_address, city)After:
Section titled “After:”city = "London"for building in buildings: addresses.append(building.street_address, city)Explanation:
Section titled “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.