Skip to content

Hoist Repeated If Condition

Sourcery refactoring id: hoist-repeated-if-condition


Move a repeated condition to a parent if block.


if x < 5 and y < 10:
    grid = range(10)
if x < 5 and y < 100:
    grid = range(100)


if x < 5:
    if y < 10:
        grid = range(10)
    if y < 100:
        grid = range(100)


Don't repeat yourself! Although nested code is normally discouraged, in this case it is easier to see the relationships between conditions.

See also: lift-duplicated-conditional, the related refactoring for if..elif blocks.