rspec/rules/S2836/python/rule.adoc

57 lines
1.7 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
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.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
----
from typing import List
def search_first_number_without_break(elements: List[str]):
for elt in elements:
if elt.isnumeric():
return elt
else: # Noncompliant. This will be executed every time
raise ValueError("List does not contain any number")
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
----
from typing import List
def search_first_number_with_break(elements: List[str]):
for elt in elements:
if elt.isnumeric():
break
else:
raise ValueError("List does not contain any number")
return elt
----
or
----
from typing import List
def search_first_number_without_else(elements: List[str]):
for elt in elements:
if elt.isnumeric():
return elt
raise ValueError("List does not contain any number")
----
2021-04-28 16:49:39 +02:00
== See
* https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops[Python documentation - break and continue Statements, and else Clauses on Loops]
ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]