A more controllable version of PyList_Sort

Currently in the Python C API, PyList_Sort doesn’t expose some underlying functionality in list_sort_impl. I’m mainly interested in having support for the key function, but the reverse parameter is also not currently exposed by PyList_Sort. I’m interested in writing a patch to add in a new function, maybe something like PyList_SortAdvanced (to preserve backwards compatibility since C doesn’t support function overloading) that exposes all the underlying functionality in list_sort_impl so it is easier to do things like sort lists containing multiple/more complex data types that the default key function fails on. Since this would be my first CPython contribution, I figured I’d discuss design decisions here first. Would a patch implementing this proposal get accepted? And are there any modifications that I should make so that it fits in better with the rest of the project? Anything else I should be aware of? Thank you for your time.


I suggest you start by opening an issue for this. Have you searched the tracker for similar proposals in the past?

Often, C API functions get the Ex suffix in the first round of adding additional arguments, so consider naming it PyList_SortEx. (Even better would be something informative but not cumbersome, but that’s not easy when adding two different arguments.)

You should explain why the function would be an improvement over using the Python API (by PyObject_VectorcallMethod for example). In this case, I can imagine handling keyword arguments (and wrapping them and their names in PyObjects) would have a noticeable performance impact, but it would be good to measure it.


I’d prefer something like PyList_SortWithKey and PyList_ReverseSort instead of a non-descriptive Ex suffix.

Why not calling the sort() method with a keyword key parameter? They are plently of ways to call functions in Python: Call Protocol — Python 3.12.0a0 documentation

Is there a major performance difference with a specialized function?