Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make sortable datatype in Python?

I have a class representing something with a few fields. When a list of instances of this class is sorted, I want them to be sorted in a particular order (get a particular key from each one). I can just do list.sort(key=Classname.sortKey) and define a sortKey method, but I'd rather just do list.sort() and have it work out. I figure I can do this by overriding __cmp__. However, what do I do when I'm comparing with something that is not my data type? I figure something like...

def __cmp__(self, o):
    if isinstance(o, MyClass):
        return cmp(self.sortKey(), o.sortKey())
    return object.__cmp__(self, o) ##**wrong

but that works instead. I don't care what ordering they take in a heterogeneous list. I would just return 0 but then stuff like MyClass(...) == x is always true, for any x not an instance of MyClass.

like image 735
Claudiu Avatar asked Feb 02 '23 23:02

Claudiu


1 Answers

Check out http://wiki.python.org/moin/HowTo/Sorting/

You want to override __lt__ in your class for the built in sort function to work the way you described.

like image 54
Andrew Clark Avatar answered Feb 05 '23 16:02

Andrew Clark