iCart iCart - 18 days ago 5
Python Question

How to use await in a python lambda

I'm trying to do something like this:

mylist.sort(key=lambda x: await somefunction(x))


But i get this error:

SyntaxError: 'await' outside async function


Which makes sense because the lambda is not async.

I tried to use
async lambda x: ...
but that throws a
SyntaxError: invalid syntax
.

Pep 492 states:


Syntax for asynchronous lambda functions could be provided, but this construct is outside of the scope of this PEP.


But i could not find out if that syntax was implemented in CPython.

Is there a way to declare an async lambda, or to use an async function for sorting a list?

Answer

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]