A condition of an if-elif chain repeats an earlier one

tx0/python:duplicate-conditiondefaultwarningbug

What it finds

if a: ... elif a: ...: a condition that repeats an earlier one of the same chain is false whenever it is reached, so its branch never runs. Usually one of the two was meant to test something else.

Between two conditions of a chain only conditions run. The chain is followed only as long as none of them can change what a later one reads: it ends at a condition that calls, awaits, yields or assigns anything. Conditions without names, such as if 0:, are constant on purpose and left alone.

From the rule's source, duplicate_condition.rs.

Example from the rule's tests
def f(kind, n, items):    if kind == "a":        n = 1    elif kind == "b":        n = 2    elif kind == "a":tx0 reports: is tested earlier in this chain, so this branch never runs        n = 3    if n > 0 and items:        pass    elif (n > 0 and items):tx0 reports: n > 0 and items is tested earlier        pass    if n:        pass    elif items[0]:        pass    elif n:tx0 reports: n is tested earlier        pass    if items.pop():        pass    elif items.pop():        pass    if n:        pass    elif (n := n - 1):        pass    elif n:        pass    if 0:        pass    elif 0:        pass    if n:        pass    else:        if n:            pass    return n
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 in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/python:duplicate-condition" = "off"

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:duplicate-condition] reason="..."

tx0 explain tx0/python:duplicate-condition shows the same in the terminal. Found a false positive? Report it.