rspec/rules/S5744/python/rule.adoc

64 lines
1.5 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
Implementing the special method ``++__ne__++`` is not equivalent to implementing the special method ``++__eq__++``. By default ``++__ne__++`` will call ``++__eq__++``, but the default implementation of ``++__eq__++`` does not call ``++__ne__++``.
This rule raises an issue when the special method ``++__ne__++`` is implemented but not the ``++__eq__++`` method.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,python]
2021-04-28 16:49:39 +02:00
----
class Ne:
def __ne__(self, other): # Noncompliant.
return False
myvar = Ne() == 1 # False. __ne__ is not called
myvar = 1 == Ne() # False. __ne__ is not called
myvar = Ne() != 1 # False
myvar = 1 != Ne() # False
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,python]
2021-04-28 16:49:39 +02:00
----
# Recommended, as __ne__ delegates to __eq__ by default
class Eq:
def __eq__(self, other):
return True
myvar = Eq() == 1 # True
myvar = 1 == Eq() # True
myvar = Eq() != 1 # False. __eq__ is called
myvar = 1 != Eq() # False. __eq__ is called
# OR if __ne__ needs a special implementation
class Eq:
def __eq__(self, other):
return True
def __ne__(self, other):
return False
----
2021-04-28 16:49:39 +02:00
:link-with-uscores1: https://docs.python.org/3/reference/datamodel.html#object.__ne__
== Resources
2021-04-28 16:49:39 +02:00
* Python documentation - {link-with-uscores1}[the ++__ne__++ special method]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::highlighting.adoc[]
endif::env-github,rspecator-view[]