flake8-simplify icon indicating copy to clipboard operation
flake8-simplify copied to clipboard

[Adjust Rule] SIM901 case where bool could be useful

Open jamesbraza opened this issue 1 year ago • 0 comments

Desired change

  • Rule(s): SIM901
  • Adjustment: the below code snippet is a false positive SIM901

Explanation

from typing import Literal, TypeAlias

Sign: TypeAlias = Literal[-1, 0, 1]


def sign(x) -> Sign:
    """
    Extract the sign (-1 if negative, 0 if zero, 1 if positive).

    SEE: https://stackoverflow.com/a/41411231
    """
    return bool(x > 0) - bool(x < 0)

If x were int/float, then the SIM901 should be thrown, as the bool cast is unnecessary.

However, since __lt__/__gt__ can return non-bool if overridden, a bool cast is useful here.

Conclusion: I think flake8-simplify should examine the type of x for an overridden __lt__/__gt__ before throwing SIM901.

jamesbraza avatar Feb 15 '23 22:02 jamesbraza