[issue39210] Sorting falls back to use __gt__ when __lt__ is not present

Tim Peters report at bugs.python.org
Sat Jan 4 21:19:49 EST 2020


Tim Peters <tim at python.org> added the comment:

It's hard to be clearer without being annoyingly wordy.  The truth is that sort does all comparisons by calling the CAPI:

    PyObject_RichCompareBool(v, w, Py_LT)`

Sorting doesn't know (or care) how `PyObject_RichCompareBool()` is implemented.  The closest Python equivalent is:

    bool(v < w)

although then you also have to be clear that `bool` refers to the builtin function of that name.

Regardless, the sorting docs certainly aren't the place to explain how `v < w` is implemented.  For example, that it _may_ end up calling `w.__gt__(v)` has nothing to do with sorting - instead that's about the semantics of comparison operators, regardless of context.

Since, best I can recall, nobody has asked about this before, perhaps the docs don't need "improvement" ;-)  If they do, then I'm with Mark:  the _intent_ was to say "if you want a class to implement its own sorting order, then it's sufficient to implement `__lt__` alone, and then sorting will use only that comparison operator if the list contains only instances of that class".

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue39210>
_______________________________________


More information about the Python-bugs-list mailing list