[Python-ideas] a sorting protocol dunder method?

Chris Barker chris.barker at noaa.gov
Sun Dec 3 18:06:02 EST 2017

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:


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

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


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?




Christopher Barker, Ph.D.

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 at noaa.gov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20171203/32f1e423/attachment.html>

More information about the Python-ideas mailing list