假设我有一个功能:
def f(x):
return {"x": x}
我可以创建一个高阶函数,其行为如下:def augment(func):
def augmented_function(x):
return {**func(x), "metadata": "test"}
return augmented_function
然后augment(f)(1)
将返回 {"x": 1, "metadata": "test"}
.但是如果
f
是一个异步协程,这个增强函数不起作用( RuntimeWarning: coroutine 'f' was never awaited
和 TypeError: 'coroutine' object is not a mapping
) - 我希望增强函数是一个可以等待的协程:async def f(x):
return {"x": x}
def augment_async(coro):
xxx
augment_async(f)(1) # Should return <coroutine object xxx>
await augment_async(f)(1) # Should return {"x": 1, "metadata": "test"}
有谁知道怎么写augment_async
在这种情况下?谢谢。
编辑 :
奖金问题。
怎么写
augment_async
如 await augment_async(f(1))
返回 {"x": 1, "metadata": "test"}
?
最佳答案
做内部函数就足够了async
,以便它可以 await
包装的功能:
def augment_async(func):
async def augmented_function(x):
return {**await func(x), "metadata": "test"}
return augmented_function
await augment_async(f)(1) # evaluates to {"x": 1, "metadata": "test"}
“增强”实例化的协程
f(1)
,单层就足够了: async def direct_async(coro):
return {**await coro, "metadata": "test"}
请注意,与 augment_async
不同,它为协程生成工厂,direct_async
直接产生一个协程——它的结果可能是 await
只编过一次。
关于python - 异步协程上的高阶函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64115747/