Annoying behaviour of the != operator

Jordan Rastrick jrastrick at student.usyd.edu.au
Wed Jun 8 14:24:08 EDT 2005


Well, I don't really want the objects to be comparable. In fact, to
quote that PEP you linked:

      An additional motivation is that frequently, types don't have a
      natural ordering, but still need to be compared for equality.
      Currently such a type *must* implement comparison and thus define
      an arbitrary ordering, just so that equality can be tested.

I don't want to order the objects. I just want to be able to say if one
is equal to the other.

Here's the justification given:

      The == and != operators are not assumed to be each other's
      complement (e.g. IEEE 754 floating point numbers do not satisfy
      this).  It is up to the type to implement this if desired.
      Similar for < and >=, or > and <=; there are lots of examples
      where these assumptions aren't true (e.g. tabnanny).

Well, never, ever use equality or inequality operations with floating
point numbers anyway, in any language, as they are notoriously
unreliable due to the inherent inaccuracy of floating point. Thats
another pitfall, I'll grant, but its a pretty well known one to anyone
with programming experience. So I don't think thats a major use case.

Are there any other reasonable examples people can give where it makes
sense for != and == not to be each other's complement?

Besides, the argument given doesn't justfiy the approach taken. Even if
you want to allow objects, in rare cases, to override __ne__ in a way
thats inconsistent with __eq__, fine, do so. But thats no reason for
Python not to fall back on __eq__ in the cases where __ne__ is not
defined, rather than reverting to object identity comparison (at least
I assume thats what its doing)

To draw a parallel:

In Java, the compareTo method in a class is allowed to be inconsistent
with the equals method, but those who write such code are advised to
heavily advertise this fact in their documentation and source, so as
not to catch unwary users off guard.

In Python, the *default* behaviour is for the equals and not equals
operations to disagree if the __eq__ method happens to be overriden
(which it definitely should be in a great number of cases).

Surely this isn't the right way to do things.

How many classes out there that have the following redundant,
cluttering piece of code?

def __ne__(self, other):
   return not self.__eq__(other)

Worse still, how many classes don't have this code, but should, and are
therefore harbouring highly confusing potential bugs?

Unless someone can explain some sort of problem that arises from having
!= take advantage of a __eq__ method where present, I'd suggest that it
should do so in Python 2.5.

I'd be surprised if such a change broke so much as a single line of
existing Python code.




More information about the Python-list mailing list