Annoying behaviour of the != operator

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


Just because a behaviour is documented, doesn't mean its not counter
intutitive, potentially confusing, and unnessecary.

I have spent a fair amount of time reading the Python docs. I have not
yet memorised them. I may have read this particular section of the
reference manual, or I may have not, I can't remember. This is the
first time I've had cause to override the __eq__ operator, and so the
first time I've encountered the behaviour in a concrete setting, which
I feel is a far more effective way to learn than to read all the
documentation cover to cover.

Where are the 'number of situations' where __ne__ cannot be derived
from __eq__? Is it just the floating point one? I must admit, I've
missed any others.

And no, I don't think I really want Python to assume anything much -
explicit is better than implicit after all. If I don't override __eq__,
or __gt__, or __cmp__, i certainly don't expect Python to infer the
behaviour I want.

But I explicitly provided a method to test equality. And look at the
plain english meaning of the term "Not equals" I think its pretty
reasonable

As far as __gt__, __lt__, __ge__, and the rest go, the answer is
simple. Anyone defining things the 'obvious' way would override
__cmp__, and sidestep the whole issues. Those who want the less obvious
behaviour of can provide it explicitly.

But as PEP207 says, you shouldn't have to override cmp if you don't
want to provide an arbitrary ordering. And its the people doing the
non-obvious thing, having __ne__ and __eq__ inconsistent, who should
have to code it and state it explicitly.

If want an orderable object, I'll just define __cmp__. If I want an
equal-comparable object, I should just be able to define __eq__. If I
want anything fancy, I can go ahead and explicitly write methods for
__gt__, __ne__, etc.




More information about the Python-list mailing list