Numeric comparison anomaly

Paul Rubin http
Wed Feb 19 13:28:22 CET 2003

I want to define an "infinite" numeric object, that's greater than
any regular number.  I do the obvious (Python 2.2):

    >>> class _infinity:
    ...   def __lt__(self, n): return 0
    ...   def __gt__(self, n): return 1
    >>> infinity = _infinity()
    >>> infinity < 9
    >>> infinity > 99999
    >>> 99999 < infinity

So far so good.  But here comes the surprise:

    >>> infinity >= 3

I wouldn't have predicted this from the description in the docs.  It
turns out that since there's no __ge__ method and no __cmp__ method,
the interpreter compared the machine addresses of the infinity object
and the "3" object.  The comparison came out one way but could have
come out the other way (or maybe I might have defined "minus infinity"
instead of infinity).  It could have been hard to discover this bug by

Anyway, the right way to implement infinity is with

   def __cmp__(self, n): return 1

I only figured all this out after starting to write this post to ask
what was causing the >= anomaly.  I decided to post anyway, as a
cautionary tale.

More information about the Python-list mailing list