Skip to content

Merge nested if statements

Sourcery refactoring id: merge-nested-ifs


Merges together multiple nested if conditions into one


if a:
    if b:
        return c


if a and b:
    return c


Too much nesting can make code difficult to understand, and this is especially true in Python, where there are no brackets to help out with the delineation of different nesting levels.

Reading deeply nested code is confusing, since you have to keep track of which conditions relate to which levels. We therefore strive to reduce nesting where possible, and the situation where two if conditions can be combined using and is an easy win.

Back to top