Skip to content

Hoist Repeated If Condition

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-repeated-if-condition

Section titled “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.