Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to just implement __lt__ for a class that will be sorted?

Tags:

python

sorting

Suppose instances of my ClassA will end up in a data structure and we know sorted() will be called on it. It's someone else's code that'll call sorted() so I can't specify a sorting function but I can implement whatever methods are appropriate on ClassA.

It appears to me that

def __lt__(self, other): 

is sufficient and that I don't need implement the other five or so methods (qt,eq,le,ge,ne).

Is this sufficient?

like image 642
Matthew Lund Avatar asked Jan 10 '12 00:01

Matthew Lund


People also ask

Can you use sorted on a string?

Definition and Usage The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically. Note: You cannot sort a list that contains BOTH string values AND numeric values.

Is Python sorted () stable?

sort() and sorted() in python are “stable sorts”, meaning that it'll preserve the existing order when faced with a tie.

Can Python list be sorted?

Python list sort() function can be used to sort a List in ascending, descending, or user-defined order.


1 Answers

PEP 8 recommends against this practice. I also recommend against it because it is a fragile programming style (not robust against minor code modifications):

Instead, consider using the functools.total_ordering class decorator to do the work:

@total_ordering class Student:     def __eq__(self, other):         return ((self.lastname.lower(), self.firstname.lower()) ==                 (other.lastname.lower(), other.firstname.lower()))     def __lt__(self, other):         return ((self.lastname.lower(), self.firstname.lower()) <                 (other.lastname.lower(), other.firstname.lower())) 
like image 80
Raymond Hettinger Avatar answered Oct 21 '22 23:10

Raymond Hettinger