__cmp__ should be reintroduced to Python
By chys on August 11th, 2009A lot of people think this decision to drop __cmp__ from Python sucks. (1 2)
The cmp argument is also dropped from list.sort and sorted. Some people explain that some programmers used to use cmp when it is more convenient and efficient to use key. By dropping cmp, poor programmers are forced to use key. On the other hand, almost all comparators found in practice are actually based on some kind of key function.
Well, theoretically this probably is true: something.sort(key=locale.strxfrm) is better than something.sort(cmp=locale.strcoll).
BUT, what can I do if I only have a third-party comparator?
I have a Python script where I use vercmp, provided in the source of Gentoo Portage, to sort a list of Gentoo packages. No corresponding verkey is provided. So now, in Python 3, I have to either write a verkey myself, or use the following ugly and inefficient workaround:
class VerKey:
def __init__(self,str):
self.str = str
def __lt__(self,other):
return vercmp(self.str, other.str) < 0
versions.sort (key = VerKey)
Related posts:
Tags: Python
