# [issue6431] Fraction fails equality test with a user-defined type

Mark Dickinson report at bugs.python.org
Fri Jul 17 00:10:04 CEST 2009

```Mark Dickinson <dickinsm at gmail.com> added the comment:

[Jeffrey]
> In particular, the idea was that all Reals would (by default) be
> comparable to each other, even if they didn't know about each other.

Understood, but I don't think this is an attainable goal.  I don't see
any reasonable way to make it happen without doing significant guessing,
or expanding the numbers ABC in some way.

At the moment, __eq__(a, b) falls back to 'float(a) == b' when b is not
a float or an instance of Rational.  This seems problematic to me for a
couple of reasons:

1. The conversion to float loses information.  As a result, we lose (a)
transitivity of equality, (b) well-behaved hashing (x == y no longer
implies hash(x) == hash(y)), and (c) consistency between == and the
other comparison operators.

2. This fallback shuts out the other class even in cases where the other
class *does* know how to handle the comparison.  So there's no way for
another class to 'play nice' with the Fraction type and implement exact
comparisons even if it wants to.

Here's an example of 1, on Python 2.6.  (bigfloat is a home-built
wrapper for the MPFR library.)

newton:~ dickinsm\$ python2.6
Python 2.6.2 (r262:71600, Jun 17 2009, 09:08:27)
[GCC 4.0.1 (Apple Inc. build 5490)] on darwin
>>> from bigfloat import BigFloat
>>> from fractions import Fraction
>>> x = Fraction(2**60-1)
>>> y = Fraction(2**60+1)
>>> z = BigFloat(2**60)
>>> x == z
True
>>> y == z
True
>>> x == y
False
>>> hash(x) == hash(z)
False

I just don't see any reasonable way to make comparisons 'automatically'
work:  one of the classes has to know how to handle both types, or else
there's just going to be a lot of guesswork involved.  So it seems
better to simply return NotImplemented in these cases.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue6431>
_______________________________________
```