-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathbuiltins.py
437 lines (318 loc) · 9.38 KB
/
builtins.py
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# Copyright 2022 Amethyst Reese
# Licensed under the MIT license
"""
Async-compatible versions of builtin functions for iterables.
These functions intentionally shadow their builtins counterparts,
enabling use with both standard iterables and async iterables, without
needing to use if/else clauses or awkward logic. Standard iterables
get wrapped in async generators, and all functions are designed for
use with `await`, `async for`, etc.
"""
import asyncio
import builtins
from enum import Enum
from typing import (
Any,
AsyncIterable,
AsyncIterator,
Callable,
cast,
Iterable,
List,
Optional,
overload,
Set,
Tuple,
Union,
)
from . import asyncio as ait_asyncio
from .helpers import maybe_await, Orderable
from .types import (
AnyIterable,
AnyIterator,
AnyStop,
MaybeAwaitable,
R,
T,
T1,
T2,
T3,
T4,
T5,
)
class Sentinel(Enum):
"""
:meta private:
"""
MISSING = object()
async def all(itr: AnyIterable[MaybeAwaitable[Any]]) -> bool:
"""
Return True if all values are truthy in a mixed iterable, else False.
The iterable will be fully consumed and any awaitables will
automatically be awaited.
Example::
if await all(it):
...
"""
return builtins.all(await ait_asyncio.gather_iter(itr))
async def any(itr: AnyIterable[MaybeAwaitable[Any]]) -> bool:
"""
Return True if any value is truthy in a mixed iterable, else False.
The iterable will be fully consumed and any awaitables will
automatically be awaited.
Example::
if await any(it):
...
"""
return builtins.any(await ait_asyncio.gather_iter(itr))
def iter(itr: AnyIterable[T]) -> AsyncIterator[T]:
"""
Get an async iterator from any mixed iterable.
Async iterators will be returned directly.
Async iterables will return an async iterator.
Standard iterables will be wrapped in an async generator yielding
each item in the iterable in the same order.
Examples::
async for value in iter(range(10)):
...
"""
if isinstance(itr, AsyncIterator):
return itr
if isinstance(itr, AsyncIterable):
return itr.__aiter__()
async def gen() -> AsyncIterator[T]:
for item in cast(Iterable[T], itr):
yield item
return gen()
@overload
async def next(itr: AnyIterator[T]) -> T: # pragma: no cover
...
@overload
async def next(itr: AnyIterator[T1], default: T2) -> Union[T1, T2]: # pragma: no cover
...
async def next(
itr: AnyIterator[T1], default: Union[T2, Sentinel] = Sentinel.MISSING
) -> Union[T1, T2]:
"""
Return the next item of any mixed iterator.
Calls builtins.next() on standard iterators, and awaits itr.__anext__()
on async iterators.
Example::
value = await next(it)
"""
try:
if isinstance(itr, AsyncIterator):
return await itr.__anext__()
try:
return builtins.next(itr)
except StopIteration:
raise StopAsyncIteration
except StopAsyncIteration:
if default is Sentinel.MISSING:
raise
return default
async def list(itr: AnyIterable[T]) -> List[T]:
"""
Consume a mixed iterable and return a list of items in order.
Example::
await list(range(5))
-> [0, 1, 2, 3, 4]
"""
return [item async for item in iter(itr)]
async def tuple(itr: AnyIterable[T]) -> Tuple[T, ...]:
"""
Consume a mixed iterable and return a tuple of items in order.
Example::
await tuple(range(5))
-> (0, 1, 2, 3, 4)
"""
# Suboptimal, but tuple can't be created from AsyncIterable directly.
return builtins.tuple(await list(itr))
async def set(itr: AnyIterable[T]) -> Set[T]:
"""
Consume a mixed iterable and return a set of items.
Example::
await set([0, 1, 2, 3, 0, 1, 2, 3])
-> {0, 1, 2, 3}
"""
return {item async for item in iter(itr)}
async def enumerate(
itr: AnyIterable[T], start: int = 0
) -> AsyncIterator[Tuple[int, T]]:
"""
Consume a mixed iterable and yield the current index and item.
Example::
async for index, value in enumerate(...):
...
"""
index = start
async for item in iter(itr):
yield index, item
index += 1
async def map(fn: Callable[[T], R], itr: AnyIterable[T]) -> AsyncIterator[R]:
"""
Modify item of a mixed iterable using the given function or coroutine.
Example::
async for response in map(func, data):
...
"""
# todo: queue items eagerly
async for item in iter(itr):
yield await maybe_await(fn(item))
@overload
async def max(
itr: AnyIterable[Orderable], *, key: Optional[Callable] = None
) -> Orderable: # pragma: no cover
pass
@overload
async def max(
itr: AnyIterable[Orderable], *, default: T, key: Optional[Callable] = None
) -> Union[Orderable, T]: # pragma: no cover
pass
async def max(itr: AnyIterable[Orderable], **kwargs: Any) -> Any:
"""
Return the largest item in an iterable or the largest of two or more arguments.
Example::
await max(range(5))
-> 4
"""
for k in kwargs:
if k not in ("key", "default"):
raise ValueError(f"kwarg {k} not supported")
value: Orderable
vkey: Any
keyfunc = kwargs.get("key", None)
it = iter(itr)
try:
value = await next(it)
if keyfunc:
vkey = keyfunc(value)
except StopAsyncIteration:
if "default" in kwargs:
return kwargs["default"]
raise ValueError("iterable is empty and no default value given")
if keyfunc:
async for item in it:
ikey = keyfunc(item)
if ikey > vkey:
value = item
vkey = ikey
else:
async for item in it:
if item > value:
value = item
return value
@overload
async def min(
itr: AnyIterable[Orderable], *, key: Optional[Callable] = None
) -> Orderable: # pragma: no cover
pass
@overload
async def min(
itr: AnyIterable[Orderable], *, default: T, key: Optional[Callable] = None
) -> Union[Orderable, T]: # pragma: no cover
pass
async def min(itr: AnyIterable[Orderable], **kwargs: Any) -> Any:
"""
Return the smallest item in an iterable or the smallest of two or more arguments.
Example::
await min(range(5))
-> 0
"""
for k in kwargs:
if k not in ("key", "default"):
raise ValueError(f"kwarg {k} not supported")
value: Orderable
vkey: Any
keyfunc = kwargs.get("key", None)
it = iter(itr)
try:
value = await next(it)
if keyfunc:
vkey = keyfunc(value)
except StopAsyncIteration:
if "default" in kwargs:
return kwargs["default"]
raise ValueError("iterable is empty and no default value given")
if keyfunc:
async for item in it:
ikey = keyfunc(item)
if ikey < vkey:
value = item
vkey = ikey
else:
async for item in it:
if item < value:
value = item
return value
async def sum(itr: AnyIterable[T], start: Optional[T] = None) -> T:
"""
Compute the sum of a mixed iterable, adding each value with the start value.
Example::
await sum(generator())
-> 1024
"""
value: T
if start is None:
value = cast(T, 0) # emulate stdlib but still type nicely for non-ints
else:
value = start
async for item in iter(itr):
value += item # type: ignore # mypy doesn't know T + T
return value
@overload
def zip(__iter1: AnyIterable[T1]) -> AsyncIterator[Tuple[T1]]: # pragma: no cover
pass
@overload
def zip(
__iter1: AnyIterable[T1], __iter2: AnyIterable[T2]
) -> AsyncIterator[Tuple[T1, T2]]: # pragma: no cover
pass
@overload
def zip(
__iter1: AnyIterable[T1], __iter2: AnyIterable[T2], __iter3: AnyIterable[T3]
) -> AsyncIterator[Tuple[T1, T2, T3]]: # pragma: no cover
pass
@overload
def zip(
__iter1: AnyIterable[T1],
__iter2: AnyIterable[T2],
__iter3: AnyIterable[T3],
__iter4: AnyIterable[T4],
) -> AsyncIterator[Tuple[T1, T2, T3, T4]]: # pragma: no cover
pass
@overload
def zip(
__iter1: AnyIterable[T1],
__iter2: AnyIterable[T2],
__iter3: AnyIterable[T3],
__iter4: AnyIterable[T4],
__iter5: AnyIterable[T5],
) -> AsyncIterator[Tuple[T1, T2, T3, T4, T5]]: # pragma: no cover
pass
@overload
def zip(
__iter1: AnyIterable[Any],
__iter2: AnyIterable[Any],
__iter3: AnyIterable[Any],
__iter4: AnyIterable[Any],
__iter5: AnyIterable[Any],
__iter6: AnyIterable[Any],
*__iterables: AnyIterable[Any],
) -> AsyncIterator[Tuple[Any, ...]]: # pragma: no cover
pass
async def zip(*itrs: AnyIterable[Any]) -> AsyncIterator[Tuple[Any, ...]]:
"""
Yield a tuple of items from mixed iterables until the shortest is consumed.
Example::
async for a, b, c in zip(i, j, k):
...
"""
its: List[AsyncIterator[Any]] = [iter(itr) for itr in itrs]
while True:
values = await asyncio.gather(
*[it.__anext__() for it in its], return_exceptions=True
)
if builtins.any(isinstance(v, AnyStop) for v in values):
break
yield builtins.tuple(values)