Reintroduce Else
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: reintroduce-else
Section titled “Sourcery refactoring id: reintroduce-else”Description:
Section titled “Description:”Lift code into else after break in control flow
Before:
Section titled “Before:”summer_hats = []for hat in hats: if hat in WINTER_HATS: continue summer_hats.append(hat)After:
Section titled “After:”summer_hats = []for hat in hats: if hat in WINTER_HATS: continue else: summer_hats.append(hat)Explanation:
Section titled “Explanation:”Where the body of an if statement ends with a break in the control flow, such
as a continue, return or raise, the subsequent statements can be lifted
into the else clause. On its own this change does not improve the code, so
Sourcery will only suggest it where it unlocks furher improvements. In the
example above once the code has been lifted into the else the conditional can
be inverted and the continue removed, which then lets the for loop be
converted into a list comprehension.