Last if statement guard¶
Sourcery refactoring id: last-if-guard
¶
Description:¶
Convert the final conditional into a guard clause
Before:¶
def f(a=None):
if a is None:
return 42
else:
# some long calculations
var = (i 2 for i in range(a))
return sum(var)
After:¶
def f(a=None):
if a is None:
return 42
# some long calculations
var = (i 2 for i in range(a))
return sum(var)
Explanation:¶
A common code pattern is to have some clauses at the start of a function, to check whether certain conditions have been fulfilled and return early or raise an exception if not.
While this is perfectly valid code, it can run into problems with excessive nesting, particularly if the rest of the function is fairly long.
Here we can take advantage of the fact that we don't need the else
if the main
body of the if
breaks the control flow by ending with return
or raise
.
Rewriting the function as shown here is logically equivalent.
Using a guard condition, or multiple guard conditions, in this way now doesn't cause the rest of the function to be indented. In general the less we have to deal with indents the easier the code is to understand.