python - 异步协程上的高阶函数
问题描述
假设我有一个功能:
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
,以便它可以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
编辑一次。
推荐阅读
- android-studio - Android Gradle 同步失败问题 Android Studio 3.1.4 & gradle 4.4
- css - Bootstrap 似乎弄乱了我的导航栏
- c# - 将 NextResult 函数与 datareader 一起使用时出错
- javascript - 从 API 数据分配嵌套数组对象
- javascript - if 和 else 都在嵌套循环中执行
- youtube-api - 如何使用令牌从 2 个不同的 youtube 配置文件执行操作
- java - 将 JDO 项目迁移到谷歌云端点 v2,服务器返回 NoClassDefFoundError
- typescript - 将数组传递给 TypeScript 中的可变参数函数
- android - 带有 TabLayout 的片段内的 ScrollView 不滚动?
- ruby-on-rails - Ruby on Rails - 未初始化的常量 SiteController::API