Guard
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: guard
Section titled “Sourcery refactoring id: guard”Description:
Section titled “Description:”Adds in guard clause to a conditional
Before:
Section titled “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:
Section titled “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:
Section titled “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"