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?
Advertisement
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]
Note that await
expressions in list comprehensions are only supported in Python 3.6+. If you’re using 3.5, you can do the following:
mylist_annotated = [] for x in mylist: mylist_annotated.append((await some_function(x), x)) mylist_annotated.sort() mylist = [x for key, x in mylist_annotated]