Make synchronous generator from an asynchronous generator

Julien Salort listes at salort.eu
Thu Mar 15 15:35:37 EDT 2018


Hello,


I have recently got the need to convert a synchronous function to 
asynchronous function because I needed to run three of them 
concurrently. Since I am using Python 3.6, I used async def and asyncio 
and that has worked out great. Thank you guys for making this possible.

Because I wanted to keep the synchronous function for scripts which used 
it, without unnecessarily duplicating the code, I built also a 
synchronous function from this new asynchronous one, like that:

def acquire_to_files(self, *args, **kwargs):
     loop = asyncio.get_event_loop()
     loop.run_until_complete(self.acquire_to_files_async(*args, **kwargs))
     loop.close()


So far, it works fine. I am quite happy.

I can await acquire_to_files_async in situations where I need 
concurrency, and call acquire_to_files in situations where I don't, and 
no code is duplicated.


Now I wish to do the same game with a generator (which happens to be 
called by the acquire_to_files_async function). So I made it into an 
asynchronous generator, and it works as expected.

My problem: how do I proceed if I wish to build a synchronous generator 
from this asynchronous generator ?

(for situations where concurrency is not needed)

i.e. what is the equivalent of the above snippet for generators ?


Thanks,


Julien


PS: I was surprised however that enumerate does not work when applied to 
an asynchronous generator, i.e.:

async for ii, img in enumerate(async_gen()):

     pass

raises TypeError: 'async_gen' object is not iterable.





More information about the Python-list mailing list