All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.py.rules.python.S2836.html Maven / Gradle / Ivy

There is a newer version: 4.23.0.17664
Show newest version

This rule raises an issue when a loop with an else clause doesn’t contain any break statement in its body.

Why is this an issue?

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.

How to fix it

Add a break statement to the loop body containing an else clause or remove the else clause.

Code examples

Noncompliant code example

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")

Compliant solution

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")

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy