S1940 should not propose code that leads to infinite recursion (e.g., avoid in `__ne__`)

  • What language is this for? Python
  • Which rule? S1940
  • Why do you believe it’s a false-positive/false-negative? Because following the advice leads to infinite recursion.
  • Are you using
    • SonarLint? VS Code, v4.11.1
  • How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)
class Int:
    def __init__(self, value: int) -> None:
        super().__init__()
        self.value = value

    def __eq__(self, other: "Int") -> bool:
        return (self.value + 10) ** 2 == other.value

    def __ne__(self, other: "Int") -> bool:
        return not self == other

print(Int(90) != Int(10000))

Now, following the advice to use self != other in __ne__ leads to

RecursionError: maximum recursion depth exceeded

(And you may ask, why is he implementing __ne__ when implementing __eq__ usually sufficies? Because when inheriting from a builtin, one inherits both __eq__ and __ne__ and has to override both.)

Hello @bers,

Thank you for reporting this false positive. It makes a lot of sense that the rule should not trigger in this case. I created SONARPY-2247 to fix this.

Cheers,
Guillaume