Welcome, guest | Sign In | My Account | Store | Cart

The following mixin implements the full suite of rich comparison operators if __cmp__ is defined. See http://docs.python.org/ref/customization.html

Python, 23 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class RichCmpMixin(object):
    """
    Define __cmp__, and inherit from this class to provide full rich
    comparisons.
    """

    def __eq__(self, other):
        return self.__cmp__(other)==0
    
    def __ne__(self, other):
        return self.__cmp__(other)!=0

    def __lt__(self, other):
        return self.__cmp__(other)==-1
    
    def __le__(self, other):
        return self.__cmp__(other)!=1

    def __gt__(self, other):
        return self.__cmp__(other)==1

    def __ge__(self, other):
        return self.__cmp__(other)!=-1

The __cmp__ method is sufficient to provide comparisons between user-defined classes. However, inheriting from a base class (such as a builtin) which already provides the rich-comparison methods will cause the derrived __cmp__ not to be used.

Probably needs testing.

4 comments

Tim Delaney 15 years, 8 months ago  # | flag

__cmp__ can return other values. The return values from __cmp__ are negative (less than), 0 (equals) or positive (greater than).

You therefore can't just compare with -1, 0 and 1 - you need to check < 0, 0 and > 0.

Steven Bethard 15 years, 8 months ago  # | flag

Sorry, why would you want this? If you define __cmp__, you can already use your object with <, >, !=, etc. so you shouldn't need any of the rich comparisons defined.

A more useful mixin would be one that defines all the rich comparisons if you just define __eq__ and __lt__. (Python doesn't fill in the missing comparison operators because for some types you can't assume that not &lt; implies >=.)

Peter Fein (author) 14 years, 1 month ago  # | flag

Good question. I don't remember why I wrote this.

Trent Mick 12 years, 8 months ago  # | flag

@steven: My understanding is that __cmp__ is going away in Python 3. I think it is gone as of Python 3.0.1.

Created by Peter Fein on Thu, 30 Mar 2006 (PSF)
Python recipes (4591)
Peter Fein's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks