1

When comparing ints and floats, Python 3 seems to take a bit of liberty:

>>> 1 == 1.0
True
>>> 1.0 == 1
True

I work on implementation of dozenal (base-12) numbers, and have overridden the __eq__ method to emulate the same behavior, and it almost works:

>>> a = Dozenal(1)
>>> a
DozenalInt('1')
>>> a == 1
debug_print: DozenalInt('1').__eq__(1) called
True
>>> 1 == a
debug_print: DozenalInt('1').__eq__(1) called
True
>>> a == 1.0
debug_print: DozenalInt('1').__eq__(1.0) called
True
>>> 1.0 == a
False

Why does it not try to call the reverse equality test in the last case, as it clearly does in others?

PS

__eq__ code really isn’t much to look at:

def __eq__(self, other):
    print('debug_print: {}.__eq__({}) called'.format(self.__repr__(), other.__repr__()))
    other = Dozenal._verify_other(other)
    if self.is_integer() and other.is_integer():
        return int(self) == int(other)
    return self._doz_cipher == other._doz_cipher

def _verify_other(other):
    if isinstance(other, Dozenal):
        return other
    elif isinstance(other, (int, float, str)):
        return Dozenal(other)
    else:
        return NotImplemented
7
  • 1
    The solution was already posted on this question: "https://stackoverflow.com/questions/38434094/reversed-comparison-operator-in-python" Commented May 26, 2017 at 13:40
  • Am I to understand that float’s __eq__ is broken (does not return NotImplemented), but int’s __eq__ works fine? Is that an oversight, or an expected behavior? Commented May 26, 2017 at 13:59
  • And, as a consequence, am I to understand that there is no way to make this work with the default == operator? Commented May 26, 2017 at 14:03
  • @CBlew, no, the OP's code was broken in that post as the __eq__ of their class is responsible for doing any comparisons involving it. Commented May 26, 2017 at 14:03
  • @ForceBru, and no direct solution was offered in that thread, only a workaround that would use a custom function instead of ==. Right? Commented May 26, 2017 at 14:06

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.