Python 3.0, rich comparisons and sorting order

Andrew Dalke adalke at
Tue Sep 21 23:29:42 CEST 2004

Carlos Ribeiro wrote:
> Given all the arguments, I'm changing my approach to the sorting
> problem. My proposal is that sortable objects should provide a __key__
> method. 

class Filename:
   def __init__(self, filename):
     self.filename = filename
   def __cmp__(self, other):
     x = cmp(os.path.getsize(self.filename),
     if x != 0:
       return x
     my_file = open(self.filename, "rb")
     other_file = open(other.filename, "rb")
     while 1:
       my_read =
       other_read =
       x = cmp(my_read, other_read)
       if x != 0:
         return x
       if not other_read:
         return 1
       if not my_read:
         return -1

filenames = map(Filename,
                 ["/etc/passwd", "/home/dalke/file.txt", ...])
sorted_filenames = [x.filename for x in filenames]

How would I do that with a __key__?  The only
solution would be to read the contents of all the
files into memory.

				dalke at

More information about the Python-list mailing list