Skip to content

Guard

Sourcery refactoring id: guard

Description:

Adds in guard clause to a conditional

Before:

def set_hat_details(hat):
    if hat.stylish and is_summer_hat(hat):
        hat.tag = "SUMMER"
    elif not hat:
        pass
    elif hat.stylish and is_winter_hat(hat):
        hat.tag = "WINTER"

After:

def set_hat_details(hat):
    if not hat:
        return

    if hat.stylish and is_summer_hat(hat):
        hat.tag = "SUMMER"
    elif hat.stylish and is_winter_hat(hat):
        hat.tag = "WINTER"

Explanation:

Often one option within an if..elif conditional will have no effect, and hence have only a pass within it. Where there is no further code within the block afterwards it is possible to extract this branch out as a guard condition. This can then sometimes allow further refinements to be made to the if..elif statements. Sourcery only suggests this refactoring if it unlocks such further changes - for example in the above case it would be combined with lift-duplicated-conditional to give the following output:

def set_hat_details(hat):
    if not hat:
        return
    if hat.stylish:
        if is_summer_hat(hat):
            hat.tag = "SUMMER"
        elif is_winter_hat(hat):
            hat.tag = "WINTER"