Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use asynchronous generator in Python 3.6?

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
like image 477
SS_Rebelious Avatar asked Sep 20 '18 17:09

SS_Rebelious


People also ask

How do I make an asynchronous code in Python?

In Python, we can do this using the async keyword before the function definition. Execution of this coroutine results in a coroutine object.

What is asynchronous generator in Python?

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.

What is the syntax for an async generator?

Async arrow functions async () => {} Generator functions function*() {} Async generator functions async function*() {}

Which module can be used to implement asynchronous communication in Python3?

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.


1 Answers

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.

like image 194
Patrick Haugh Avatar answered Nov 15 '22 20:11

Patrick Haugh