Annoying behaviour of the != operator

Jordan Rastrick jrastrick at student.usyd.edu.au
Wed Jun 8 13:02:52 EDT 2005


Can anybody please give me a decent justification for this:

class A(object):
    def __init__(self, a):
        self.a = a

    def __eq__(self, other):
        return self.a == other.a

s = A(3)
t = A(3)

>>> print s == t
True
>>> print s != t
True

I just spent a long, long time tracking down a bug in a program that
results from this behaviour.

Surely the != operator should, if no __ne__ method is present for
either object, check to see if an __eq__ method is defined, and if so,
return its negation?

Actually, that brings me to a wider question - why does __ne__ exist at
all? Surely its completely inconsistent and unnessecary to have
seperate equals and not equals methods on an object? a != b should just
be a short way of writing not (a == b). The fact the two can give a
different answer seems to me to be utterly unintuitive and a massive
pitfall for beginners (such as myself).




More information about the Python-list mailing list