I'm trying to do something like this:
mylist.sort(key=lambda x: await somefunction(x))
SyntaxError: 'await' outside async function
async lambda x: ...
SyntaxError: invalid syntax
Syntax for asynchronous lambda functions could be provided, but this construct is outside of the scope of this PEP.
You can't. There is no
async lambda, and even if there were, you coudln't pass it in as key function to
list.sort(), since a key function will be called as a synchronous function and not awaited. An easy work-around is to annotate your list yourself:
mylist_annotated = [(await some_function(x), x) for x in mylist] mylist_annotated.sort() mylist = [x for key, x in mylist_annotated]