Junior — Middle
Explain the mechanism of asynchronous generators in Python and their usage features.
sobes.tech AI
Answer from AI
Asynchronous generators in Python are generators that allow the use of await inside the generator body and return values asynchronously using yield.
They are defined using async def and use yield or yield from together with await. Asynchronous generators are useful when iterating over data that arrives with a delay or requires waiting, such as when working with network or I/O.
Features:
- Used in an asynchronous context with
async for. - Allow performing asynchronous operations inside the generator.
- Help save resources by processing data as it arrives.
Example:
import asyncio
async def async_generator():
for i in range(3):
await asyncio.sleep(1) # simulate an asynchronous operation
yield i
async def main():
async for value in async_generator():
print(value)
asyncio.run(main())
Here, async_generator asynchronously generates values with a delay, and async for allows them to be received sequentially.