Numeric comparison anomaly

Gary Herron gherron at islandtraining.com
Thu Feb 20 22:30:28 CET 2003


On Thursday 20 February 2003 12:38 pm, sismex01 at hebmex.com wrote:
> > From: Piet van Oostrum [mailto:piet at cs.uu.nl]
> > Sent: Thursday, February 20, 2003 4:56 AM
> >
> > >>>>> Gerrit Holl <gerrit at nl.linux.org> (GH) schreef:
> >
> > GH> You can use the __cmp__ overloader:
> >
> > GH>  21 >>> class A:
> > GH>  21 ...  def __cmp__(self, other):
> > GH>  21 ...   return 1
> > GH>  21 ...
> > GH>  22 >>> A() > 5
> > GH> True
> > GH>  23 >>> A() < 9
> > GH> False
> > GH>  24 >>> A() >= 3
> > GH> True
> >
> > >>> inf = A()
> > >>> inf > inf
> >
> > True
> >
> > >>> inf == inf
> >
> > False
>
> This is correct, or wrong?
>
> -gustavo

This is correct of course.  By having __cmp__ return 1 *always*, you
are saying inf is greater than *anything* else without regard to what
the other thing is.  (Note that your __cmp__ does not even look at the
second argument.)  It will never compare equal to anything (__cmp__
would need to return a zero for that).

Thus

  inf > ...any python object...

returns True because __cmp__ returns 1 (meaning "is greater than") and

  inf == ...any python object...

returns False because __cmp__ returns 1 (meaning "is greater than" --
not "equal to").


Did you perhaps miss that __cmp__ must return one of three casses:
  negative integer: meaning "self is less than    other"
  0:                meaning "self is equal to     other"
  positive integer: meaning "self is greater than other"


Gary Herron






More information about the Python-list mailing list