Add __ne__ built-in function

In Python 3 __ne__ by default delegates to __eq__ and inverts the
result, but in Python 2 they urge you to define __ne__ when you define
__eq__ for it to work properly [1]. There are no implied relationships
among the comparison operators. The truth of x==y does not imply that
x!=y is false. Accordingly, when defining __eq__(), one should also
define __ne__() so that the operators will behave as expected.

[1]https://docs.python.org/2/reference/datamodel.html#object.__ne__

Change-Id: I6ad4b07911f6c8236dfcd048aceebd44cd760fe2
This commit is contained in:
howardlee 2016-11-16 19:14:52 +08:00 committed by David Stanek
parent 42a6bf8dfc
commit 7666acbb1e
3 changed files with 18 additions and 0 deletions

View File

@ -125,6 +125,12 @@ class Opt(object):
self.default == other.default and
self.metavar == other.metavar)
# NOTE: This function is only needed by Python 2. If we get to point where
# we don't support Python 2 anymore, this function should be removed.
def __ne__(self, other):
"""Define inequality operator on option parameters."""
return not self.__eq__(other)
@property
def _all_opts(self):
return itertools.chain([self], self.deprecated)

View File

@ -76,6 +76,12 @@ class BoolType(object):
# hack around oslo.config equality comparison
return type(self) == type(other)
# NOTE: This function is only needed by Python 2. If we get to point where
# we don't support Python 2 anymore, this function should be removed.
def __ne__(self, other):
"""Define inequiality for many bool types."""
return not self.__eq__(other)
def __call__(self, value):
return str(value).lower() in ('1', 'true', 't', 'yes', 'y')

View File

@ -135,6 +135,12 @@ class TestResponse(requests.Response):
"""Define equiality behavior of request and response."""
return self.__dict__ == other.__dict__
# NOTE: This function is only needed by Python 2. If we get to point where
# we don't support Python 2 anymore, this function should be removed.
def __ne__(self, other):
"""Define inequiality behavior of request and response."""
return not self.__eq__(other)
@property
def text(self):
return self.content