Remove Unnecessary 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: remove-unnecessary-else
Section titled “Sourcery refactoring id: remove-unnecessary-else”Description:
Section titled “Description:”Remove unnecessary else after guard condition
Before:
Section titled “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:
Section titled “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:
Section titled “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.