Annoying behaviour of the != operator

Kay Schluehr kay.schluehr at gmx.net
Wed Jun 8 16:05:20 EDT 2005



Jordan Rastrick wrote:
> 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.

For certain classes you can define behaviour like this:

>>> x = Expr()
>>> let(x+2 == 0)
x+2==0
>>> solve(let(x+2==0))
x==-2
>>> x.val
-2

My Expr class implements __eq__ and __ne__ in the following way:

    def __eq__(self,other):
        self._wrapPredicate("==",other)
        return self._iseq(other)

    def __ne__(self,other):
        self._wrapPredicate("!=",other)
        return not self._iseq(other)

It would be hard to use operator overloading to create expressions if
there are a lot of implicite assumptions. On the other hand I agree
with you about the default behaviour of __ne__ and that it should be
related locally to the class that overloads __eq__ and not to some
global interpreter defined behaviour. 

Kay




More information about the Python-list mailing list