I need to process several pages of data from server. I would like to make a generator for it like this. Unfortunately I get TypeError: 'async_generator' object is not iterable
async def get_data():
i = 0
while i < 3:
i += 1
data = await http_call() # call to http-server here
yield data
data = [i for i in get_data()] # inside a loop
Next variant raises TypeError: object async_generator can't be used in 'await' expression
data = [i for i in await get_data()] # inside a loop
In Python, we can do this using the async keyword before the function definition. Execution of this coroutine results in a coroutine object.
Asynchronous generators Simply put these are generators written in asynchronous functions (instead of def function(..) they use async def function(..) So to convert next_delay function from previous example we just add async keyword before def.
Async arrow functions async () => {} Generator functions function*() {} Async generator functions async function*() {}
Python 3's asyncio module provides fundamental tools for implementing asynchronous I/O in Python. It was introduced in Python 3.4, and with each subsequent minor release, the module has evolved significantly. This tutorial contains a general overview of the asynchronous paradigm, and how it's implemented in Python 3.7.
Use async for
in your comprehension. See PEP 530 -- Asynchronous Comprehensions
data = [i async for i in get_data()]
Depending on what version of Python you're using, this may only be available in async def
functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With