如何在python lambda中使用await [英] 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:无效语法
.
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?
推荐答案
您不能.没有异步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中使用await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!