I was refactoring some old code of mine and came across of this:
alist.sort(cmp_items)
def cmp_items(a, b):
if a.foo > b.foo:
return 1
elif a.foo == b.foo:
return 0
else:
return -1
The code works (and I wrote it some 3 years ago!) but I cannot find this thing documented anywhere in the Python docs and everybody uses sorted() to implement custom sorting. Can someone explain why this works?
sorted()andsort()offer custom sorting in much the same way, modulo the difference in calling convention.keyparameter is preferred over passing acmpfunction. (The later is not even implemented in Python 3)foo, otherwise it blows up. Better to define a custom__lt__()method for your class, thensorted()andlist.sort()will work out-of-the-box. (Btw, objects no longer need to define__cmp__(), just__lt__(). See this