no more comparisons

Carl Banks pavlovevidence at gmail.com
Wed Mar 12 22:42:39 CET 2008


On Mar 12, 4:51 pm, Alan Isaac <ais... at american.edu> wrote:
> I was surprised to see that
> comparison is slated for death
> in Python 3000.
>
> For example:http://www.python.org/dev/peps/pep-3100/
>         list.sort() and builtin.sorted() methods: eliminate cmp parameter [27] [done]


Hmm, wasn't aware they were taking it that far.  You should almost
always avoid using the cmp parameter because it's very inefficient;
instead, look at the key parameter which is a function that maps
objects in a your sequence to a sort key and sorts on that.

So instead of (for a simple example):

s.sort(cmp=lambda a,b: cmp(a.get_id(),b.get_id()))

You would use:

s.sort(key=lambda a:a.get_id())

(However, there are rare cases where you can't easily map your items
to a sortable builtin.  I suppose in those cases you'll have to use a
custom comparison proxy.  But I digress.)


> But there is a rumor of a PEP to restore comparisons.http://mail.python.org/pipermail/python-3000/2008-January/011764.html
>
> Is that going anywhere?

No.


> Also, what is the core motivation for removing this functionality?

The basically replaced it with a better one.  Instead of the cmp
methods above, use the key method.  Instead of __cmp__ method for
overriding object operators, use the rich comparison methods: __lt__,
__gt__, and so on.

Python 2.x currently implements both cmp and rich comparisons at the
same time, but that creates a lot of underlying complexity, so they
got rid of it.


Carl Banks



More information about the Python-list mailing list