1
|
|
|
"""Utility function.""" |
2
|
|
|
from typing import ( |
3
|
|
|
Any, |
4
|
|
|
AsyncGenerator, |
5
|
|
|
AsyncIterable, |
6
|
|
|
Awaitable, |
7
|
|
|
Callable, |
8
|
|
|
Iterable, |
9
|
|
|
TypeVar, |
10
|
|
|
Union, |
11
|
|
|
) |
12
|
|
|
|
13
|
|
|
|
14
|
|
|
__all__ = ['amap', 'afilter', 'run'] |
15
|
|
|
|
16
|
|
|
T = TypeVar('T') |
17
|
|
|
|
18
|
|
|
|
19
|
|
|
async def amap( |
20
|
|
|
corofunc: Callable[[Any], Awaitable[T]], iterable: Union[AsyncIterable, Iterable] |
21
|
|
|
) -> AsyncGenerator[T, None]: |
22
|
|
|
"""Map an async function onto an iterable or an async iterable. |
23
|
|
|
|
24
|
|
|
# Parameters |
25
|
|
|
corofunc (Callable[[Any], Awaitable[T]]): coroutine function |
26
|
|
|
iterable (Union[AsyncIterable, Iterable]): iterable or async iterable collection |
27
|
|
|
which will be applied. |
28
|
|
|
|
29
|
|
|
# Returns |
30
|
|
|
AsyncGenerator[T]: an async iterator of corofunc(item) |
31
|
|
|
|
32
|
|
|
# Example |
33
|
|
|
```[i async for i in amap(inc, afilter(even, [0, 1, 2, 3, 4]))]``` |
34
|
|
|
|
35
|
|
|
""" |
36
|
|
|
if isinstance(iterable, AsyncIterable): # if hasattr(iterable, '__aiter__'): |
37
|
|
|
async for item in iterable: |
38
|
|
|
yield await corofunc(item) |
39
|
|
|
else: |
40
|
|
|
for item in iterable: |
41
|
|
|
yield await corofunc(item) |
42
|
|
|
|
43
|
|
|
|
44
|
|
|
async def afilter( |
45
|
|
|
corofunc: Callable[[Any], Awaitable[bool]], iterable: Union[AsyncIterable, Iterable] |
46
|
|
|
) -> AsyncGenerator[T, None]: |
47
|
|
|
"""Filter an iterable or an async iterable with an async function. |
48
|
|
|
|
49
|
|
|
# Parameters |
50
|
|
|
corofunc (Callable[[Any], Awaitable[bool]]): filter async function |
51
|
|
|
iterable (Union[AsyncIterable, Iterable]): iterable or async iterable collection |
52
|
|
|
which will be applied. |
53
|
|
|
|
54
|
|
|
# Returns |
55
|
|
|
(AsyncGenerator[T]): an async iterator of item which satisfy corofunc(item) == True |
56
|
|
|
|
57
|
|
|
# Example |
58
|
|
|
```[i async for i in amap(inc, afilter(even, [0, 1, 2, 3, 4]))]``` |
59
|
|
|
|
60
|
|
|
""" |
61
|
|
|
if isinstance(iterable, AsyncIterable): # if hasattr(iterable, '__aiter__'): |
62
|
|
|
async for item in iterable: |
63
|
|
|
if await corofunc(item): |
64
|
|
|
yield item |
65
|
|
|
else: |
66
|
|
|
for item in iterable: |
67
|
|
|
if await corofunc(item): |
68
|
|
|
yield item |
69
|
|
|
|
70
|
|
|
|
71
|
|
|
# pylint: disable=unused-import |
72
|
|
|
try: |
73
|
|
|
import curio # noqa: F401 |
74
|
|
|
from contextvars import copy_context |
75
|
|
|
|
76
|
|
|
def run(kernel, target, *args): |
77
|
|
|
"""Curio run with independent contextvars.""" |
78
|
|
|
return copy_context().run(kernel.run, target, *args) |
79
|
|
|
|
80
|
|
|
|
81
|
|
|
except Exception: # pylint: disable=broad-except |
82
|
|
|
|
83
|
|
|
def run(kernel, target, *args): |
84
|
|
|
raise RuntimeError('curio not installed!') |
85
|
|
|
|