Comparing objects - is there a maximum object?

Mel Wilson mwilson at the-wire.com
Fri Sep 5 01:00:20 CEST 2003


In article <7bdbb1a6.0309041124.6801b755 at posting.google.com>,
cbrew at acm.org (Chris Brew) wrote:
> [ ... ]   so I want endmarker to be a generic
>maximum object.

   I've used the following.. a module I call limitcases.py.
It ensures that limit objects compare equal to each other,
and have distinctive hash values, so they work as sort keys
and can be used as dictionary keys.

        Regards.        Mel.


"""limitcases.py
Provides objects which compare less-than and greater-than any other object.
Useful for sentinels, or for initial values in maximum- or minimum-finding
routines.
"""

class Lowest:
    "Instances of Lowest compare < any object except each other."
    def __cmp__ (self, other):
        if isinstance (other, Lowest):
            return 0
        return -1

    def __hash__ (self):
        return id (Lowest)
# class Lowest


class Highest:
    "Instances of Highest compare > any object except each other."
    def __cmp__ (self, other):
        if isinstance (other, Highest):
            return 0
        return 1

    def __hash__ (self):
        return id (Highest)
# class Highest


if __name__ == '__main__':
    print Lowest()
    print Highest()
    print

    # An application can provide its own printable representation.
    Lowest.__str__ = lambda x: "-Infinity"
    Highest.__str__ = lambda x: "+Infinity"

    x = [1, Highest(), 2, Lowest(), 0, Highest(), Lowest()]
    x.sort()
    print 'X = ',
    for v in x:
        print v,
    print
    print
    print'X:', x
    print




More information about the Python-list mailing list