| 1 |
from asyncio import CancelledError, Event, Task, ensure_future, wait |
| 2 |
from concurrent.futures import FIRST_COMPLETED |
| 3 |
from inspect import isasyncgen, isawaitable |
| 4 |
from types import TracebackType |
| 5 |
from typing import Any, AsyncIterable, Callable, Optional, Set, Type, Union |
| 6 |
|
| 7 |
__all__ = ["MapAsyncIterator"] |
| 8 |
|
| 9 |
|
| 10 |
# noinspection PyAttributeOutsideInit |
| 11 |
class MapAsyncIterator: |
| 12 |
"""Map an AsyncIterable over a callback function. |
| 13 |
|
| 14 |
Given an AsyncIterable and a callback function, return an AsyncIterator which |
| 15 |
produces values mapped via calling the callback function. |
| 16 |
|
| 17 |
When the resulting AsyncIterator is closed, the underlying AsyncIterable will also |
| 18 |
be closed. |
| 19 |
""" |
| 20 |
|
| 21 |
def __init__(self, iterable: AsyncIterable, callback: Callable) -> None: |
| 22 |
self.iterator = iterable.__aiter__() |
| 23 |
self.callback = callback |
| 24 |
self._close_event = Event() |
| 25 |
|
| 26 |
def __aiter__(self) -> "MapAsyncIterator": |
| 27 |
"""Get the iterator object.""" |
| 28 |
return self |
| 29 |
|
| 30 |
async def __anext__(self) -> Any: |
| 31 |
"""Get the next value of the iterator.""" |
| 32 |
if self.is_closed: |
| 33 |
if not isasyncgen(self.iterator): |
| 34 |
raise StopAsyncIteration |
| 35 |
value = await self.iterator.__anext__() |
| 36 |
else: |
| 37 |
aclose = ensure_future(self._close_event.wait()) |
| 38 |
anext = ensure_future(self.iterator.__anext__()) |
| 39 |
|
| 40 |
try: |
| 41 |
pending: Set[Task] = ( |
| 42 |
await wait([aclose, anext], return_when=FIRST_COMPLETED) |
| 43 |
)[1] |
| 44 |
except CancelledError: |
| 45 |
# cancel underlying tasks and close |
| 46 |
aclose.cancel() |
| 47 |
anext.cancel() |
| 48 |
await self.aclose() |
| 49 |
raise # re-raise the cancellation |
| 50 |
|
| 51 |
for task in pending: |
| 52 |
task.cancel() |
| 53 |
|
| 54 |
if aclose.done(): |
| 55 |
raise StopAsyncIteration |
| 56 |
|
| 57 |
error = anext.exception() |
| 58 |
if error: |
| 59 |
raise error |
| 60 |
|
| 61 |
value = anext.result() |
| 62 |
|
| 63 |
result = self.callback(value) |
| 64 |
|
| 65 |
return await result if isawaitable(result) else result |
| 66 |
|
| 67 |
async def athrow( |
| 68 |
self, |
| 69 |
type_: Union[BaseException, Type[BaseException]], |
| 70 |
value: Optional[BaseException] = None, |
| 71 |
traceback: Optional[TracebackType] = None, |
| 72 |
) -> None: |
| 73 |
"""Throw an exception into the asynchronous iterator.""" |
| 74 |
if self.is_closed: |
| 75 |
return |
| 76 |
if isinstance(type_, BaseException): |
| 77 |
value = type_ |
| 78 |
type_ = type(value) |
| 79 |
traceback = value.__traceback__ |
| 80 |
athrow = getattr(self.iterator, "athrow", None) |
| 81 |
if athrow: |
| 82 |
await athrow(type_ if value is None else value) |
| 83 |
else: |
| 84 |
await self.aclose() |
| 85 |
if value is None: |
| 86 |
if traceback is None: |
| 87 |
raise type_ # pragma: no cover |
| 88 |
value = type_ if isinstance(value, BaseException) else type_() |
| 89 |
if traceback is not None: |
| 90 |
value = value.with_traceback(traceback) |
| 91 |
raise value |
| 92 |
|
| 93 |
async def aclose(self) -> None: |
| 94 |
"""Close the iterator.""" |
| 95 |
if not self.is_closed: |
| 96 |
aclose = getattr(self.iterator, "aclose", None) |
| 97 |
if aclose: |
| 98 |
try: |
| 99 |
await aclose() |
| 100 |
except RuntimeError: |
| 101 |
pass |
| 102 |
self.is_closed = True |
| 103 |
|
| 104 |
@property |
| 105 |
def is_closed(self) -> bool: |
| 106 |
"""Check whether the iterator is closed.""" |
| 107 |
return self._close_event.is_set() |
| 108 |
|
| 109 |
@is_closed.setter |
| 110 |
def is_closed(self, value: bool) -> None: |
| 111 |
"""Mark the iterator as closed.""" |
| 112 |
if value: |
| 113 |
self._close_event.set() |
| 114 |
else: |
| 115 |
self._close_event.clear() |