Iterate an async generator synchronously, from a producer thread.
The producer runs the generator on its own event loop and stays at most
maxsize items ahead (a bounded queue). close(), also called when the
iterator is garbage-collected, stops the producer and aclose()s the generator.
Source code in src/anyenv/calling/async_executor.py
| class LazyAsyncIterator[T]:
"""Iterate an async generator synchronously, from a producer thread.
The producer runs the generator on its own event loop and stays at most
``maxsize`` items ahead (a bounded queue). ``close()``, also called when the
iterator is garbage-collected, stops the producer and ``aclose()``s the generator.
"""
def __init__(
self, async_iter_func: Callable[[], AsyncIterator[T]], *, maxsize: int = 16
) -> None:
self._producer = _Producer(async_iter_func, maxsize)
self._finished = False
def __iter__(self) -> Self:
return self
def __next__(self) -> T:
if self._finished:
raise StopIteration
if self._producer.thread is None:
self._producer.start()
item = self._producer.queue.get()
if item is _END:
self._finished = True
raise StopIteration
if isinstance(item, _Failure):
raise item.error
return item # type: ignore[no-any-return]
def close(self) -> None:
"""Stop the producer and close the generator; returns once both are done."""
self._finished = True
self._producer.signal_stop()
self._producer.join()
def __del__(self) -> None:
# No join: a finalizer must not block (it may run in any thread).
with contextlib.suppress(Exception):
self._producer.signal_stop()
|
close
Stop the producer and close the generator; returns once both are done.
Source code in src/anyenv/calling/async_executor.py
| def close(self) -> None:
"""Stop the producer and close the generator; returns once both are done."""
self._finished = True
self._producer.signal_stop()
self._producer.join()
|