Skip to content

Instantly share code, notes, and snippets.

@bindreams
Created July 4, 2024 19:03
Show Gist options
  • Save bindreams/d928096cb84c7c167e8244d22ec6346b to your computer and use it in GitHub Desktop.
Save bindreams/d928096cb84c7c167e8244d22ec6346b to your computer and use it in GitHub Desktop.
import asyncio
async def async_iterate(sync_iterable):
"""Convert a syncronized iterable into an async one.
Taken from https://stackoverflow.com/q/76991812
"""
# to_thread errors if StopIteration raised in it. So we use a sentinel to detect the end
done_sentinel = object()
it = iter(sync_iterable)
while (value := await asyncio.to_thread(next, it, done_sentinel)) is not done_sentinel:
yield value
def async_generator(func):
"""A decorator that converts a generator function into an async generator."""
async def wrapper(*args, **kwargs):
async for item in async_iterate(func(*args, **kwargs)):
yield item
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment