【发布时间】:2020-09-29 08:28:27
【问题描述】:
假设我有一个函数:
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,然后在里面等待func -
TypeError: 'coroutine' object is not callable。你有完整的代码示例吗?
标签: python python-asyncio