Every branch of an if-else or conditional expression is the same

tx0/python:identical-branchesrecommendedwarningbug

What it finds

if c: f() with else: f(): when every branch of an if does the same, the condition decides nothing. Usually one branch was copied and not changed. The same goes for a conditional expression whose two outcomes are the same, as x if c else x.

A chain with elif branches is reported only when it ends in an else and every branch is the same: giving each case its own branch even where two do the same is a common way to list the cases.

Some branches are the same on purpose. Type checkers and compilers such as mypyc treat the same code differently in each branch of a condition that tests sys.version_info, sys.platform, TYPE_CHECKING, isinstance or issubclass, so those are left alone, and so is a match whose cases all do the same, a common placeholder for cases still to come. Others keep the branches apart with a comment that says why, which is why the rule is not in the default tier.

From the rule's source, identical_branches.rs.

Example from the rule's tests
import sysfrom typing import TYPE_CHECKING  def f(ok, n, items):    if ok:tx0 reports: both branches of this if do the same        n = g(n)    else:        n = g(n)    if n > 1:tx0 reports: every branch of this if chain does the same        items.append(n)    elif n > 0:        items.append(n)    else:        items.append(n)    if n > 1:        items.append(n)    elif n > 0:        items.append(n)    if n > 1:        items.append(n)    elif n > 0:        items.append(n)    else:        items.append(1)    if ok:        n = 1    else:        n = 2    x = n if ok else ntx0 reports: both outcomes of this conditional expression are n    y = n if ok else n + 1    if ok:tx0 reports: both branches of this if do the same        n = g(n)    else:        # The same, but with a comment.        n = g(n)    if sys.version_info >= (3, 12):        from os import path    else:        from os import path    if isinstance(items, list):        n = len(items)    else:        n = len(items)    if TYPE_CHECKING:        z = 1    else:        z = 1    match n:        case 1:            n = g(n)        case _:            n = g(n)    return x, y, z, path  def g(n):    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 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:identical-branches" = "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:identical-branches] reason="..."

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