首页 > 解决方案 > 异步协程上的高阶函数

问题描述

假设我有一个功能:

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 awaitedTypeError: '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"}

标签: pythonpython-asyncio

解决方案


制作内部函数就足够了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的 distinct 直接生成协程 - 它的结果只能被await编辑一次。


推荐阅读