Python 3.0, rich comparisons and sorting order

Peter Otten __peter__ at web.de
Wed Sep 22 11:15:36 CEST 2004


Steven Bethard wrote:

> 'Course rather than wrap your expression tuples in a class to define the
> __cmp__ function, it seems like a more reasonable solution might be to
> make the arbitrary cmp decision in the mapping class (the one implemented
> as a BTree).  

Yes, and that would give you a lot more flexibility, as sorting by an
attribute is almost as common as a "natural" sort (Not counting lists
consisting entirely of items of the same type).

> If __cmp__ starts raising TypeErrors, your code could do
> something like:
> 
> def insert(self, val):
>     try:
>         c = cmp(self.val, val)
>     except TypeError:
>         c = -1 # self.val and val were not of the same type
>                # make some arbitrary decision here
>     ... # insert according to cmp result
 
I'd rather pass the comparison function to __init__(self, cmp=cmp) and then
do 

def insert(self, value):
    cmp = self.cmp
    # use cmp to insert value in the appropriate place

You could even provide a classical_compare that compares values like today's
default. I don't think you can seriously call self.cmp() instead of cmp()
more work. If you are concerned about the extra slot for the cmp attribute
of your custom BTree, put the default into the class.

Peter




More information about the Python-list mailing list