1

Is it possible to wrap a function around an AsyncIterator to get a (sync) Iterator?

I was able to convert an AsyncIterator to List and use it as an Iterator, but would love to not do the conversion to Int

class AsyncToSyncIterableUtils(Generic[T]):

    @staticmethod
    def sync_all(iterable: AsyncIterable[T]) -> Iterable[T]:
        results:List[T] = []
        async def _wrapper():
            async for m in iterable:
                results.append(m)
        loop = asyncio.get_event_loop()
        try:
            loop.run_until_complete(_wrapper())
        finally:
            loop.run_until_complete(loop.shutdown_asyncgens()) # see: https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.shutdown_asyncgens
            loop.close()
        return results
enzo
  • 9,861
  • 3
  • 15
  • 38
Dunes Buggy
  • 1,779
  • 1
  • 21
  • 41
  • Does this answer your question? [How to wrap asyncio with iterator](https://stackoverflow.com/questions/55132673/how-to-wrap-asyncio-with-iterator) – mkrieger1 Apr 19 '23 at 09:55

0 Answers0