假设我有一个功能:
def f(x):
return {"x": x}
Run Code Online (Sandbox Code Playgroud)
我可以创建一个高阶函数,其行为如下:
def augment(func):
def augmented_function(x):
return {**func(x), "metadata": "test"}
return augmented_function
Run Code Online (Sandbox Code Playgroud)
然后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"}
Run Code Online (Sandbox Code Playgroud)
有谁知道augment_async在这种情况下怎么写?
谢谢。
编辑:奖金问题。
augment_async比如await augment_async(f(1))return怎么写 …