How to pass additional arguments to custom python sorting function How to pass additional arguments to custom python sorting function django django

How to pass additional arguments to custom python sorting function


As Ashish points out in the comments, we first need to combine these functions, since key only accepts a single functions. If we return a sequence (list, tuple) of the function results, Python will do the right thing, only comparing later (farther right) elements if the earlier elements are equal (source).

I know of a couple ways to do this.

Using lambdas:

sortedBookList = sorted(    bookList,     key=lambda elem: (sortByName(elem),                       sortByFirstLanguage(elem, firstLanguage),                       sortByLanguages(elem, possibleLanguages)))

Using higher-order functions:

def key_combiner(*keyfuncs):  def helper(elem):    return [keyfunc(elem) for keyfunc in keyfuncs]  return helperdef sortByFirstLanguage(firstLanguage):  def helper(elem):    return elem.language == firstLanguage  # True > False  return helperdef sortByLanguages(possibleLanguages):  def helper(elem):    if elem.language in possibleLanguages:       return possibleLanguages.index(elem.language)  return helpersortedBookList = sorted(bookList,                        key=key_combiner(sortByName,                                          sortByFirstLanguage(firstLanguage),                                          sortByLanguages(possibleLanguages))

Lambdas seem cleanest to me, so that's probably what I'd use.