Reintroduce Else¶
Sourcery refactoring id: reintroduce-else
¶
Description:¶
Lift code into else
after break in control flow
Before:¶
summer_hats = []
for hat in hats:
if hat in WINTER_HATS:
continue
summer_hats.append(hat)
After:¶
summer_hats = []
for hat in hats:
if hat in WINTER_HATS:
continue
else:
summer_hats.append(hat)
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.