How to use wait in lambda python

I am 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 lambda is not asynchronous.

I tried to use async lambda x:...but it gives out SyntaxError: invalid syntax.

Pep 492 states:

Syntax for asynchronous lambda functions can be provided, but this design is beyond the scope of this PEP.

But I could not find out if this syntax was implemented in CPython.

Is there a way to declare an asynchronous lambda or use an asynchronous function to sort a list?

+9
source share
1 answer

async lambda, , list.sort(), . - :

mylist_annotated = [(await some_function(x), x) for x in mylist]
mylist_annotated.sort()
mylist = [x for key, x in mylist_annotated]

, 'await' Python 3. 6+. 3.5, :

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]
+15

Source: https://habr.com/ru/post/1661602/


All Articles