【问题标题】:Higher-order function on async coroutine异步协程上的高阶函数
【发布时间】: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 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"}

【问题讨论】:

  • 只做增强函数async,然后在里面等待func
  • TypeError: 'coroutine' object is not callable。你有完整的代码示例吗?

标签: python python-asyncio


【解决方案1】:

内部函数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 直接生成协程 - 它的结果可能只被awaited 一次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多