1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
|
"""Utilities for asynchronous iteration."""
from __future__ import annotations
from types import TracebackType
import warnings
import functools
from typing import (
TYPE_CHECKING,
AsyncContextManager,
AsyncGenerator,
AsyncIterable,
Awaitable,
Callable,
Type,
TypeVar,
AsyncIterator,
Any,
)
if TYPE_CHECKING:
from typing_extensions import ParamSpec
P = ParamSpec("P")
from contextlib import AsyncExitStack
__all__ = [
"aiter",
"anext",
"await_",
"async_",
"is_async_iterable",
"assert_async_iterable",
"is_async_iterator",
"assert_async_iterator",
"AsyncIteratorContext",
"aitercontext",
"AsyncExitStack",
]
# Magic method shorcuts
def aiter(obj: AsyncIterable[T]) -> AsyncIterator[T]:
"""Access aiter magic method."""
assert_async_iterable(obj)
return obj.__aiter__()
def anext(obj: AsyncIterator[T]) -> Awaitable[T]:
"""Access anext magic method."""
assert_async_iterator(obj)
return obj.__anext__()
# Async / await helper functions
async def await_(obj: Awaitable[T]) -> T:
"""Identity coroutine function."""
return await obj
def async_(fn: Callable[P, Awaitable[T]]) -> Callable[P, Awaitable[T]]:
"""Wrap the given function into a coroutine function."""
@functools.wraps(fn)
async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
return await fn(*args, **kwargs)
return wrapper
# Iterability helpers
def is_async_iterable(obj: object) -> bool:
"""Check if the given object is an asynchronous iterable."""
return hasattr(obj, "__aiter__")
def assert_async_iterable(obj: object) -> None:
"""Raise a TypeError if the given object is not an
asynchronous iterable.
"""
if not is_async_iterable(obj):
raise TypeError(f"{type(obj).__name__!r} object is not async iterable")
def is_async_iterator(obj: object) -> bool:
"""Check if the given object is an asynchronous iterator."""
return hasattr(obj, "__anext__")
def assert_async_iterator(obj: object) -> None:
"""Raise a TypeError if the given object is not an
asynchronous iterator.
"""
if not is_async_iterator(obj):
raise TypeError(f"{type(obj).__name__!r} object is not an async iterator")
# Async iterator context
T = TypeVar("T")
Self = TypeVar("Self", bound="AsyncIteratorContext[Any]")
class AsyncIteratorContext(AsyncIterator[T], AsyncContextManager[Any]):
"""Asynchronous iterator with context management.
The context management makes sure the aclose asynchronous method
of the corresponding iterator has run before it exits. It also issues
warnings and RuntimeError if it is used incorrectly.
Correct usage::
ait = some_asynchronous_iterable()
async with AsyncIteratorContext(ait) as safe_ait:
async for item in safe_ait:
<block>
It is nonetheless not meant to use directly.
Prefer aitercontext helper instead.
"""
_STANDBY = "STANDBY"
_RUNNING = "RUNNING"
_FINISHED = "FINISHED"
def __init__(self, aiterator: AsyncIterator[T]):
"""Initialize with an asynchrnous iterator."""
assert_async_iterator(aiterator)
if isinstance(aiterator, AsyncIteratorContext):
raise TypeError(f"{aiterator!r} is already an AsyncIteratorContext")
self._state = self._STANDBY
self._aiterator = aiterator
def __aiter__(self: Self) -> Self:
return self
def __anext__(self) -> Awaitable[T]:
if self._state == self._FINISHED:
raise RuntimeError(
f"{type(self).__name__} is closed and cannot be iterated"
)
if self._state == self._STANDBY:
warnings.warn(
f"{type(self).__name__} is iterated outside of its context",
stacklevel=2,
)
return anext(self._aiterator)
async def __aenter__(self: Self) -> Self:
if self._state == self._RUNNING:
raise RuntimeError(f"{type(self).__name__} has already been entered")
if self._state == self._FINISHED:
raise RuntimeError(
f"{type(self).__name__} is closed and cannot be iterated"
)
self._state = self._RUNNING
return self
async def __aexit__(
self,
typ: Type[BaseException] | None,
value: BaseException | None,
traceback: TracebackType | None,
) -> bool:
try:
if self._state == self._FINISHED:
return False
try:
# No exception to throw
if typ is None:
return False
# Prevent GeneratorExit from being silenced
if typ is GeneratorExit:
return False
# No method to throw
if not hasattr(self._aiterator, "athrow"):
return False
# No frame to throw
if not getattr(self._aiterator, "ag_frame", True):
return False
# Cannot throw at the moment
if getattr(self._aiterator, "ag_running", False):
return False
# Throw
try:
assert isinstance(self._aiterator, AsyncGenerator)
await self._aiterator.athrow(typ, value, traceback)
raise RuntimeError("Async iterator didn't stop after athrow()")
# Exception has been (most probably) silenced
except StopAsyncIteration as exc:
return exc is not value
# A (possibly new) exception has been raised
except BaseException as exc:
if exc is value:
return False
raise
finally:
# Look for an aclose method
aclose = getattr(self._aiterator, "aclose", None)
# The ag_running attribute has been introduced with python 3.8
running = getattr(self._aiterator, "ag_running", False)
closed = not getattr(self._aiterator, "ag_frame", True)
# A RuntimeError is raised if aiterator is running or closed
if aclose and not running and not closed:
try:
await aclose()
# Work around bpo-35409
except GeneratorExit:
pass # pragma: no cover
finally:
self._state = self._FINISHED
async def aclose(self) -> None:
await self.__aexit__(None, None, None)
async def athrow(self, exc: Exception) -> T:
if self._state == self._FINISHED:
raise RuntimeError(f"{type(self).__name__} is closed and cannot be used")
assert isinstance(self._aiterator, AsyncGenerator)
item: T = await self._aiterator.athrow(exc)
return item
def aitercontext(
aiterable: AsyncIterable[T],
) -> AsyncIteratorContext[T]:
"""Return an asynchronous context manager from an asynchronous iterable.
The context management makes sure the aclose asynchronous method
has run before it exits. It also issues warnings and RuntimeError
if it is used incorrectly.
It is safe to use with any asynchronous iterable and prevent
asynchronous iterator context to be wrapped twice.
Correct usage::
ait = some_asynchronous_iterable()
async with aitercontext(ait) as safe_ait:
async for item in safe_ait:
<block>
"""
aiterator = aiter(aiterable)
if isinstance(aiterator, AsyncIteratorContext):
return aiterator
return AsyncIteratorContext(aiterator)
|