python - 检查函数在 python 3.7 中是否是异步的
问题描述
我想在 python 中调用它之前检查一个函数是否是异步的。例如,在这里我想检查是否f
是异步的,这样 await 才有意义:
async def call_async_f(f):
assert function_is_async(f)
await f()
我该如何实施function_is_async
?我正在使用 python 3.7,它似乎有一些有趣的新异步功能,我不介意特定于 3.7 的解决方案。
解决方案
inspect检查大多数类型的异步对象,在您的情况下,它是 iscoroutinefunction
import inspect
async def call_async_f(f):
assert inspect.iscoroutinefunction(f)
await f()
推荐阅读
- javascript - 什么可能导致 redux 状态加载延迟?
- if-statement - Google Script - 正确删除 Else 语句,使其跳过/忽略
- delphi - 两个数据库日期时间字段之间的格式化时间差
- azure - 将本地映像用于 Read 3.0、Azure 认知服务、计算机视觉
- sql - 跨联接语法更新
- python - 为什么我无法访问 global 关键字之前同一块中的全局变量?
- angular - Angular API 快照,类型“IJobs”不可分配给类型“IJobs []”
- django - 我正在使用 lightsail 和 route53 部署我的站点,但出现错误请求 400
- java - 从另一种方法向数组添加/设置变量
- python - 如何将用户输入的阿拉伯语答案翻译成英语