如何在 python lambda 中使用等待 [英] How to use await in a python lambda
问题描述
我正在尝试做这样的事情:
I'm trying to do something like this:
mylist.sort(key=lambda x: await somefunction(x))
但我收到此错误:
SyntaxError: 'await' outside async function
这是有道理的,因为 lambda 不是异步的.
Which makes sense because the lambda is not async.
我尝试使用 async lambda x: ...
但这会引发 SyntaxError: invalid syntax
.
I tried to use async lambda x: ...
but that throws a SyntaxError: invalid syntax
.
Pep 492 声明:
可以提供异步 lambda 函数的语法,但此构造超出了本 PEP 的范围.
Syntax for asynchronous lambda functions could be provided, but this construct is outside of the scope of this PEP.
但我不知道该语法是否在 CPython 中实现.
But I could not find out if that syntax was implemented in CPython.
有没有办法声明异步 lambda,或者使用异步函数对列表进行排序?
Is there a way to declare an async lambda, or to use an async function for sorting a list?
推荐答案
你不能.没有async lambda
,即使有,你也不能把它作为键函数传递给list.sort()
,因为一个键函数会被调用作为一个同步函数而不是等待.一个简单的解决方法是自己注释您的列表:
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]
请注意,列表推导式中的 await
表达式仅在 Python 3.6+ 中受支持.如果您使用的是 3.5,则可以执行以下操作:
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]
这篇关于如何在 python lambda 中使用等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!