Python 3.6+typesterm
types.AsyncGeneratorType
generators and coroutines
The type of an asynchronous generator — the object returned by an async def that contains yield. It can only be iterated with async for.
Syntax
isinstance(obj, types.AsyncGeneratorType)
An async def with yield is no longer a coroutine: await does not work on it, and a plain for fails with TypeError because the object only has __aiter__/__anext__. You can iterate it only inside another async function, with async for or an async comprehension. If iteration stops at break, close the generator (contextlib.aclosing), otherwise its finally runs at some unknown moment.
Examples
import asyncio
import types
async def ticks():
for i in range(3):
yield i
async def main():
print(isinstance(ticks(), types.AsyncGeneratorType))
print([i async for i in ticks()])
asyncio.run(main())
# → True / [0, 1, 2]
async def ticks():
yield 1
try:
for i in ticks():
pass
except TypeError:
print('TypeError') # → TypeError
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy