A loop's body always leaves the loop, so it runs at most once

tx0/python:loop-runs-oncerecommendedwarningbug

What it finds

A while loop whose body always ends with break, return or raise never gets to a second pass: the loop is an if in disguise, or a statement that was meant to be inside a condition is not.

Loops that continue somewhere are left alone, since continue starts another pass. for loops are not reported: leaving one in its first pass is the common way to take the first item of an iterable or to test that it has one.

From the rule's source, loop_runs_once.rs.

Example from the rule's tests
def first_ready(queue, items):    while queue:        job = queue.pop()        breaktx0 reports: this ends every pass of the while loop, so it runs at most once    for item in items:        print(item)        break    for item in items:        if item:            continue        break    while True:        try:            return queue.get()        except IndexError:            continue    for item in items:        return item    for item in items:        break    else:        return None
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/python:loop-runs-once" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

# tx0: ignore[tx0/python:loop-runs-once] reason="..."

tx0 explain tx0/python:loop-runs-once shows the same in the terminal. Found a false positive? Report it.