org.sonar.l10n.py.rules.python.S2159.html Maven / Gradle / Ivy
Why is this an issue?
In some cases a comparison with operators ==
, or !=
will always return True or always return False. When this happens,
the comparison and all its dependent code can simply be removed. This includes:
- comparing unrelated builtin types such as string and integer.
- comparing class instances which do not implement
__eq__
or __ne__
to an object of a different type (builtin or from
an unrelated class which also doesn’t implement __eq__
or __ne__
).
Noncompliant code example
foo = 1 == "1" # Noncompliant. Always False.
foo = 1 != "1" # Noncompliant. Always True.
class A:
pass
myvar = A() == 1 # Noncompliant. Always False.
myvar = A() != 1 # Noncompliant. Always True.
Compliant solution
foo = 1 == int("1")
foo = str(1) != "1"
class Eq:
def __eq__(self, other):
return True
myvar = Eq() == 1
myvar = 1 == Eq()
myvar = Eq() != 1 # Ok. "__ne__" calls "__eq__" by default
myvar = 1 != Eq()
© 2015 - 2024 Weber Informatics LLC | Privacy Policy