python - 异步协程上的高阶函数

标签 python python-asyncio

假设我有一个功能:

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_asyncawait 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/

相关文章:

python - `create_task()`处的任务是什么时候asyncio执行的?

python - 如何使用 requests_html 异步 get() URL 列表?

python - 推荐使用 [python-lifter] 进行查询的嵌套数据结构

Python 安装卸载 easy_install

php - 在 PHP 中使用列表

python - 在 Python 3.8 中修补异步对象

python - 异步 python itertools 链接多个生成器

python - 将参数传递给 python 二进制可执行文件

python - 来自while循环的语法错误

Python - 如何取消由 python-trio 中的托儿所产生的特定任务