MartinThoma / flake8-simplify

❄ A flake8 plugin that helps you to simplify code
MIT License
187 stars 19 forks source link

[Adjust Rule] SIM901 case where bool could be useful #167

Open jamesbraza opened 1 year ago

jamesbraza commented 1 year ago

Desired change

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.