Unnecessary ‘else’ clause in loop¶
ID: py/redundant-elseKind: problemSecurity severity: Severity: warningPrecision: very-highTags: - quality - maintainability - useless-codeQuery suites: - python-security-and-quality.qls
Click to see the query in the CodeQL repository
Theelse clause of a loop (either afor or awhile statement) executes immediately after the loop terminates normally. If there is abreak statement in the loop body, then theelse clause is skipped. If there is nobreak statement, then theelse clause will always be executed after the loop, unless it exits with areturn orraise. Therefore, if there is nobreak statement in the loop body then theelse clause can be replaced with unindented code.
Generally the use ofelse clauses should be avoided where possible, as they are likely to be misunderstood.
Recommendation¶
Replace theelse clause with unindented code.
Example¶
In this example, thepointless_else function contains a redundantelse clause. Theelse clause can be simplified, as shown in theno_else function, which has the same semantics, but has noelse clause. The third example function,with_break, shows a version where theelse clause is necessary, as thebreak statement skips theelse clause.
defpointless_else(container):foritemincontainer:ifof_interest(item):returnitemelse:raiseNotFoundException()defno_else(container):foritemincontainer:ifof_interest(item):returnitemraiseNotFoundException()defwith_break(container):foritemincontainer:ifof_interest(item):found=itembreakelse:raiseNotFoundException()returnfound
References¶
Python Language Reference:The while statement.
Python Tutorial:Break and continue statements, and else clauses on loops.