Yes, you can still get these numbers in the asynchronous version, these are Asynchronous generators , you can use async for (PEP492) and asynchronous messages (PEP530) , like this, rewrite from your first example. although this requires a python version higher or equal to 3.6
import asyncio async def searching_stuff_1(): # searching yield 1 # and searching yield 2 yield 3 async def searching_stuff_2(): yield 4 yield 5 async def gen(): async for i in searching_stuff_1(): yield i async for i in searching_stuff_2(): yield i async def gen_all(): return [i async for i in gen()] if __name__ == "__main__": result = asyncio.get_event_loop().run_until_complete(gen_all()) print(result)
wanting to run two async async generators, you can use asyncio.gather .
But since asyncio.gather collects the result of coroutines in asynchronous mode, you need to combine each result from the asynchronous generator separately with async def gen2 before calling asyncio.gather.
async def gen2(coro): return [i async for i in coro()]
To prove our point, we can change searching_stuff to:
async def searching_stuff_1(): print("searching_stuff_1 begin") # searching yield 1 await asyncio.sleep(1) # and searching yield 2 yield 3 print("searching_stuff_1 end") async def searching_stuff_2(): print("searching_stuff_2 begin") yield 4 await asyncio.sleep(1) yield 5 print("searching_stuff_2 end")
and then make a move:
result = asyncio.get_event_loop().run_until_complete(gen_all()) print(result) > searching_stuff_2 begin > searching_stuff_1 begin > searching_stuff_2 end > searching_stuff_1 end > [1, 2, 3, 4, 5]
soulomoon
source share