Annoying behaviour of the != operator
newsgroups at jhrothjr.com
Thu Jun 9 00:11:29 CEST 2005
"Jordan Rastrick" <jrastrick at student.usyd.edu.au> wrote in message
news:1118259397.502842.260270 at z14g2000cwz.googlegroups.com...
> Well, I'll admit I haven't ever used the Numeric module, but since
> PEP207 was submitted and accepted, with Numeric as apparently one of
> its main motivations, I'm going to assume that the pros and cons for
> having == and ilk return things other than True or False have already
> been discussed at length and that argument settled. (I suppose theres a
> reason why Numeric arrays weren't just given the same behaviour as
> builtin lists, and then simple non-special named methods to do the
> 'rich' comparisons.)
They were - read the PEP again. That's the behavior they wanted
to get away from.
> But again, it seems like a pretty rare and marginal use case, compared
> to simply wanting to see if some object a is equal to (in a non object
> identity sense) object b.
> The current situation seems to be essentially use __cmp__ for normal
> cases, and use the rich operations, __eq__, __gt__, __ne__, and rest,
> only in the rare cases. Also, if you define one of them, make sure you
> define all of them.
> Theres no room for the case of objects where the == and != operators
> should return a simple True or False, and are always each others
> complement, but <, >= and the rest give an error. I haven't written
> enough Python to know for sure, but based on my experience in other
> languages I'd guess this case is vastly more common than all others put
> I'd be prepared to bet that anyone defining just __eq__ on a class, but
> none of __cmp__, __ne__, __gt__ etc, wants a != b to return the
> negation of a.__eq__(b). It can't be any worse than the current case of
> having == work as the method __eq__ method describes but != work by
> object identity.
To quote Calvin Coolege: You lose.
The primary open source package I work on, PyFit, always wants to
do an equal comparison, and never needs to do a not equal. It also has
no use for ordering comparisons. I do not equals as a matter of symmetry
in case someone else wants them, but I usually have no need of them.
Strict XP says I shouldn't do them without a customer request.
> So far, I stand by my suggested change.
I think most of your justification is simple chicken squaking, but write
the PEP anyway. I'd suggest tightening it to say that if __eq__ is
defined, and if neither __ne__ nor __cmp__ is defined, then use
__eq__ and return the negation if and only if the result of __eq__
is a boolean. Otherwise raise the current exception.
I wouldn't suggest the reverse, though. Defining __ne__ and not
defining __eq__ is simply perverse.
More information about the Python-list