This rule raises an issue when a loop with an else clause doesn’t contain any break statement in its body.
The else clause of a loop is skipped when a break is executed in this loop. In other words, a loop with an
else but no break statement will always execute the else part (unless of course an exception is raised or
return is used). If this is what the developer intended, it would be much simpler to have the else statement removed and its
body unindented. Thus having a loop with an else and no break is most likely an error.
Add a break statement to the loop body containing an else clause or remove the else clause.
from typing import List
def foo(elements: List[str]):
for elt in elements:
if elt.isnumeric():
return elt
else: # Noncompliant: no break in the loop
raise ValueError("List does not contain any number")
def bar(elements: List[str]):
for elt in elements:
if elt.isnumeric():
return elt
else: # Noncompliant: no break in the loop
raise ValueError("List does not contain any number")
from typing import List
def foo(elements: List[str]):
for elt in elements:
if elt.isnumeric():
break
else:
raise ValueError("List does not contain any number")
return elt
def bar(elements: List[str]):
for elt in elements:
if elt.isnumeric():
return elt
raise ValueError("List does not contain any number")