I can't believe this hasn't been brought up before, but searching the web, and python-ideas, and all the PEPs has found nothing (could be my lame google-fu), so here goes:

Recent python has moved toward a "key" function for customized sorting:

list.sort(key=key_fun)

key is also used (according to https://docs.python.org/3.6/library/functools.html#functools.cmp_to_key) in:

min(), max(), heapq.nlargest(), heapq.nsmallest(), itertools.groupby()

with this fairly broad use, it seems it's becoming a fairly universal protocol for ordering.

However, if you are writing a custom class, and want to make it "sortable", you need to define (some of) the total comparison operators, which presumably are then called O(n logn) number of times for comparisons when sorting.

Or provide a sort key function when you actually do the sorting, which requires some inside knowledge of the objects you are sorting.

But what if there was a sort key magic method:

 __key__ or __sort_key__ (or whatever)

that would be called by the sorting functions if:

no key function was specified

and

it exists

It seems this would provide a easy way to make custom classes sortable that would be nicer for end users (not writing key functions), and possibly more performant in the "usual" case.

In fact, it's striking me that there may well be classes that are defining the comparison magic methods not because they want the objects to "work" with the comparison operators, but because that want them to work with sort and min, and max, and...

hmm, perhaps a __key__ method could even be used by the comparison operators, though that could result in pretty weird results when comparing two different types.

So: has this already been brought up and rejected?

Am I imagining the performance benefits?

Is sorting-related functionally too special-case to deserve a protocol?

Thoughts?

-Chris

--

Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker@noaa.gov