Python 3.0, rich comparisons and sorting order

Andrew Dalke adalke at mindspring.com
Tue Sep 21 17:29:42 EDT 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),
             os.path.getsize(other.filename))
     if x != 0:
       return x
     my_file = open(self.filename, "rb")
     other_file = open(other.filename, "rb")
     while 1:
       my_read = xfile.read(8192)
       other_read = yfile.read(8192)
       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", ...])
filenames.sort()
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.

				Andrew
				dalke at dalkescientific.com




More information about the Python-list mailing list