[Python-ideas] __sort__ special member

Lefavor, Matthew (GSFC-582.0)[MICROTEL LLC] matthew.lefavor at nasa.gov
Fri Jul 20 18:22:46 CEST 2012


With regard to point 1: I think that changing the return type of sorted() would cause nasty surprises. If you can no longer assume that calling sorted() on any arbitrary container is going to return an indexed list, then we've lost all the advantages of Python's "duck typing."

With regard to point 2: How would this interact with the existing signature of the sorted() function? The sorted() function, as it is right now, is responsible not just for the sort algorithm, but also for defining how comparisons should work. If the comparison keys are changed, then you can't assume any sorting operation is trivial anymore. Consider the following, using a range object:

>>> import math
>>> sorted(range(10), key=math.sin)
[5, 4, 6, 0, 3, 9, 7, 1, 2, 8]

Matthew Lefavor

From: David Townshend <aquavitae69 at gmail.com<mailto:aquavitae69 at gmail.com>>
Date: Friday, July 20, 2012 12:11 PM
To: "python-ideas at python.org<mailto:python-ideas at python.org>" <python-ideas at python.org<mailto:python-ideas at python.org>>
Subject: [Python-ideas] __sort__ special member


I was quite surprised to find that nobody seems to have suggested this before, because it seems like an obvious idea. Basically, add a special method __sort__ which, if specified, is used when sorted() is called. I can think of two immediate use cases:

1. When an object wants sorted() to return something other than a list, e.g. dict.__sort__ could return an OrderedDict.
2. When there is a more efficient method of sorting a specific sequence. E.g. sorting a range object should be trivial.

Is there some obvious reason why nobody has suggested this before?  Is it worth pursuing?

David.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20120720/0f8410f6/attachment.html>


More information about the Python-ideas mailing list