首页 > 解决方案 > 检查函数在 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 的解决方案。

标签: pythonpython-asynciopython-3.7

解决方案


inspect检查大多数类型的异步对象,在您的情况下,它是 iscoroutinefunction

import inspect
async def call_async_f(f):
    assert inspect.iscoroutinefunction(f)
    await f()

推荐阅读