asyncio.iscoroutinefunction returns 异步发电机为假
asyncio.iscoroutinefunction returns False for asynchronous generator
以下异步生成器代码直接从 PEP525 中取出:
async def gen():
await asyncio.sleep(0.1)
v = yield 42
print(v)
await asyncio.sleep(0.2)
但是当我打电话时(python3.6):
print(asyncio.iscoroutinefunction(gen), asyncio.iscoroutine(gen))
我得到:
False, False
为什么异步生成器无法识别为协程函数?
是否有其他方法可以将其识别为协程函数?
你想使用 inspect.isasyncgenfunction()
(and inspect.isasyncgen()
作为调用结果 gen()
):
>>> import inspect
>>> print(inspect.isasyncgenfunction(gen), inspect.isasyncgen(gen()))
True True
异步函数和异步生成器函数之间没有类型层次关系。
此外,asyncio.iscoroutine*()
函数 存在的唯一原因 是为了支持 legacy generator-based @asyncio.coroutine
decorator,它不能用于创建异步生成器.如果您不需要支持可能仍在使用那些旧代码库(所以早于 Python 3.5),我会坚持使用 inspect.is*()
函数。
以下异步生成器代码直接从 PEP525 中取出:
async def gen():
await asyncio.sleep(0.1)
v = yield 42
print(v)
await asyncio.sleep(0.2)
但是当我打电话时(python3.6):
print(asyncio.iscoroutinefunction(gen), asyncio.iscoroutine(gen))
我得到:
False, False
为什么异步生成器无法识别为协程函数?
是否有其他方法可以将其识别为协程函数?
你想使用 inspect.isasyncgenfunction()
(and inspect.isasyncgen()
作为调用结果 gen()
):
>>> import inspect
>>> print(inspect.isasyncgenfunction(gen), inspect.isasyncgen(gen()))
True True
异步函数和异步生成器函数之间没有类型层次关系。
此外,asyncio.iscoroutine*()
函数 存在的唯一原因 是为了支持 legacy generator-based @asyncio.coroutine
decorator,它不能用于创建异步生成器.如果您不需要支持可能仍在使用那些旧代码库(所以早于 Python 3.5),我会坚持使用 inspect.is*()
函数。