Confusing problem (well, for me anyway)

Duncan Smith buzzard at urubu.freeserve.co.uk
Sat Feb 22 16:46:28 EST 2003


"Steven Taschuk" <staschuk at telusplanet.net> wrote in message
news:mailman.1045943734.17332.python-list at python.org...
> Quoth Duncan Smith:
>   [...]
> >     def __cmp__(self, other):
>   [...]
> >             if comp == size:
> >                 print 'returning 1'
> >                 return 1
> >             else:
> >                 print 'returning 0'
> >                 return 0
>   [...]
> > >>> t == t1
> > 6 6 1
> > returning 1
> > 0
>   [...]
> > I cannot see why the function returns 1 when it should return 0 (and
> > vice-versa).  How can it print 'returning 1' and then return 0?
>
> __cmp__ doesn't implement equality testing, or rather, not *just*
> equality testing.  It actually compares two objects for order:
>     >>> cmp(1,2)
>     -1
>     >>> cmp(1,1)
>     0
>     >>> cmp(2,1)
>     1
> (The built-in cmp() uses __cmp__ for objects which define it.)
>
> Returning 1 from __cmp__ means "I'm greater than that other
> object", returning 0 means "I'm equal to that other object", and
> returning -1 means "I'm less than that other object".
>
> Thus, asking
> x == y
> is the same as asking
> cmp(x, y) == 0
> whence the weirdness you see: __cmp__ returns 1, which means >,
> therefore !=, and so == yields 0.
>
> If you just want equality testing, not order testing, provide
> __eq__ and __ne__ instead.
>
> --
> Steven Taschuk                                                   w_w
> staschuk at telusplanet.net                                      ,-= U
>                                                                1 1
>

Cheers.  (I really should have spotted that.)  All sorted now.

Duncan






More information about the Python-list mailing list