Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Sort custom class without use of `key` argument?

Tags:

python

You can sort an array of myclass by using the key argument to the sorted function:

sortedlist = sorted(myclasses, key=lambda obj: obj.myproperty)

Is there a way to define a natural ordering for our class? Perhaps some magic method so that we don't have to pass in a key each time?

e.g.,

class myclass:
    def __init__(self,a,b):
        self.key1 = a
        self.key2 = b

    def __sortkey__(self):
        return self.key2

Or will it naturally work if we define __le__ perhaps?

like image 489
mpen Avatar asked Jul 28 '12 23:07

mpen


2 Answers

In addition to __cmp__, you can also do it with the so-called "rich comparison operators" __eq__, __le__, __lt__, __gt__, and __ge__. Rather than defining all of them, you can use the functools.total_ordering class decorator in 2.7+/3.1+. __cmp__ is gone in 3.x.

like image 64
Danica Avatar answered Sep 17 '22 14:09

Danica


I'd do it by overriding __cmp__

class myclass:
    def __init__(self,a,b):
        self.key1 = a
        self.key2 = b

    def __cmp__(self, other):
        return cmp(self.key2, other.key2)
like image 27
Daenyth Avatar answered Sep 19 '22 14:09

Daenyth