Created
July 4, 2024 19:03
-
-
Save bindreams/d928096cb84c7c167e8244d22ec6346b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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