Skip to content

trcks.fp.monads.awaitable

Monadic functions for collections.abc.Awaitable.

Provides utilities for functional composition of asynchronous functions.

Example
>>> import asyncio
>>> from trcks.fp.composition import pipe
>>> from trcks.fp.monads import awaitable as a
>>> async def read_from_disk() -> str:
...     await asyncio.sleep(0.001)
...     return "Hello, world!"
...
>>> def transform(s: str) -> str:
...     return f"Length: {len(s)}"
...
>>> async def write_to_disk(s: str) -> None:
...     await asyncio.sleep(0.001)
...
>>> async def main() -> str:
...     awaitable_str = read_from_disk()
...     return await pipe(
...         (
...             awaitable_str,
...             a.tap(lambda s: print(f"Read '{s}' from disk.")),
...             a.map_(transform),
...             a.tap_to_awaitable(write_to_disk),
...             a.tap(lambda s: print(f"Wrote '{s}' to disk.")),
...         ),
...     )
...
>>> output = asyncio.run(main())
Read 'Hello, world!' from disk.
Wrote 'Length: 13' to disk.
>>> output
'Length: 13'

construct(value)

Create a collections.abc.Awaitable from a value.

Parameters:

Returns:

Example
>>> import asyncio
>>> from collections.abc import Awaitable
>>> from trcks.fp.monads import awaitable as a
>>> awtbl = a.construct("Hello, world!")
>>> isinstance(awtbl, Awaitable)
True
>>> asyncio.run(a.to_coroutine(awtbl))
'Hello, world!'
Source code in src/trcks/fp/monads/awaitable.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def construct(value: _T) -> Awaitable[_T]:
    """Create a [collections.abc.Awaitable][] from a value.

    Args:
        value: The value to create the [collections.abc.Awaitable][] from.

    Returns:
        The [collections.abc.Awaitable][] created from the value.

    Example:
        >>> import asyncio
        >>> from collections.abc import Awaitable
        >>> from trcks.fp.monads import awaitable as a
        >>> awtbl = a.construct("Hello, world!")
        >>> isinstance(awtbl, Awaitable)
        True
        >>> asyncio.run(a.to_coroutine(awtbl))
        'Hello, world!'
    """
    return _construct(value)

map_(f)

Turn synchronous function into a function expecting and returning collections.abc.Awaitable.

Parameters:

Returns:

Note

The underscore in the function name helps to avoid collisions with the built-in function map.

Example
>>> import asyncio
>>> from collections.abc import Awaitable
>>> from trcks.fp.monads import awaitable as a
>>> def transform(s: str) -> str:
...     return f"Length: {len(s)}"
...
>>> transform_mapped = a.map_(transform)
>>> awaitable_input = a.construct("Hello, world!")
>>> awaitable_output = transform_mapped(awaitable_input)
>>> isinstance(awaitable_output, Awaitable)
True
>>> asyncio.run(a.to_coroutine(awaitable_output))
'Length: 13'
Source code in src/trcks/fp/monads/awaitable.py
 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
def map_(f: Callable[[_T1], _T2]) -> Callable[[Awaitable[_T1]], Awaitable[_T2]]:
    """Turn synchronous function into a function
    expecting and returning [collections.abc.Awaitable][].

    Args:
        f:
            The synchronous function to be transformed into
            a function expecting and returning a [collections.abc.Awaitable][].

    Returns:
        The given function transformed into
            a function expecting and returning a [collections.abc.Awaitable][].

    Note:
        The underscore in the function name helps to avoid collisions
        with the built-in function [map][].

    Example:
        >>> import asyncio
        >>> from collections.abc import Awaitable
        >>> from trcks.fp.monads import awaitable as a
        >>> def transform(s: str) -> str:
        ...     return f"Length: {len(s)}"
        ...
        >>> transform_mapped = a.map_(transform)
        >>> awaitable_input = a.construct("Hello, world!")
        >>> awaitable_output = transform_mapped(awaitable_input)
        >>> isinstance(awaitable_output, Awaitable)
        True
        >>> asyncio.run(a.to_coroutine(awaitable_output))
        'Length: 13'

    """

    def composed_f(value: _T1) -> Awaitable[_T2]:
        return construct(f(value))

    return map_to_awaitable(composed_f)

map_to_awaitable(f)

Turn collections.abc.Awaitable-returning function into function expecting and returning collections.abc.Awaitable.

Parameters:

Returns:

Example
>>> import asyncio
>>> from collections.abc import Awaitable
>>> from trcks.fp.monads import awaitable as a
>>> async def write_to_disk(output: str) -> None:
...     await asyncio.sleep(0.001)
...     print(f"Wrote '{output}' to disk.")
...
>>> write_to_disk_mapped = a.map_to_awaitable(write_to_disk)
>>> awaitable_input = a.construct("Hello, world!")
>>> awaitable_output = write_to_disk_mapped(awaitable_input)
>>> isinstance(awaitable_output, Awaitable)
True
>>> asyncio.run(a.to_coroutine(awaitable_output))
Wrote 'Hello, world!' to disk.
Source code in src/trcks/fp/monads/awaitable.py
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
def map_to_awaitable(
    f: Callable[[_T1], Awaitable[_T2]],
) -> Callable[[Awaitable[_T1]], Awaitable[_T2]]:
    """Turn [collections.abc.Awaitable][]-returning function into
    function expecting and returning [collections.abc.Awaitable][].

    Args:
        f:
            The [collections.abc.Awaitable][]-returning function to be transformed into
            a function expecting and returning a [collections.abc.Awaitable][].

    Returns:
        The given function transformed into
            a function expecting and returning a [collections.abc.Awaitable][].


    Example:
        >>> import asyncio
        >>> from collections.abc import Awaitable
        >>> from trcks.fp.monads import awaitable as a
        >>> async def write_to_disk(output: str) -> None:
        ...     await asyncio.sleep(0.001)
        ...     print(f"Wrote '{output}' to disk.")
        ...
        >>> write_to_disk_mapped = a.map_to_awaitable(write_to_disk)
        >>> awaitable_input = a.construct("Hello, world!")
        >>> awaitable_output = write_to_disk_mapped(awaitable_input)
        >>> isinstance(awaitable_output, Awaitable)
        True
        >>> asyncio.run(a.to_coroutine(awaitable_output))
        Wrote 'Hello, world!' to disk.
    """

    async def mapped_f(awaitable: Awaitable[_T1]) -> _T2:
        return await f(await awaitable)

    return mapped_f

tap(f)

Turn synchronous function into a function expecting a collections.abc.Awaitable and returning the same collections.abc.Awaitable.

Parameters:

Returns:

Example
>>> import asyncio
>>> from collections.abc import Awaitable
>>> from trcks.fp.monads import awaitable as a
>>> def print_string(s: str) -> None:
...     print(f"String: {s}")
...
>>> print_string_tapped = a.tap(print_string)
>>> awaitable_input = a.construct("Hello, world!")
>>> awaitable_output = print_string_tapped(awaitable_input)
>>> isinstance(awaitable_output, Awaitable)
True
>>> value = asyncio.run(a.to_coroutine(awaitable_output))
String: Hello, world!
>>> value
'Hello, world!'
Source code in src/trcks/fp/monads/awaitable.py
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
def tap(f: Callable[[_T1], object]) -> Callable[[Awaitable[_T1]], Awaitable[_T1]]:
    """Turn synchronous function into a function
    expecting a [collections.abc.Awaitable][] and
    returning the same [collections.abc.Awaitable][].

    Args:
        f:
            The synchronous function to be transformed into a function
            expecting a [collections.abc.Awaitable][] and
            returning the same [collections.abc.Awaitable][].

    Returns:
        The given function transformed into a function
            expecting a [collections.abc.Awaitable][] and
            returning the same [collections.abc.Awaitable][].

    Example:
        >>> import asyncio
        >>> from collections.abc import Awaitable
        >>> from trcks.fp.monads import awaitable as a
        >>> def print_string(s: str) -> None:
        ...     print(f"String: {s}")
        ...
        >>> print_string_tapped = a.tap(print_string)
        >>> awaitable_input = a.construct("Hello, world!")
        >>> awaitable_output = print_string_tapped(awaitable_input)
        >>> isinstance(awaitable_output, Awaitable)
        True
        >>> value = asyncio.run(a.to_coroutine(awaitable_output))
        String: Hello, world!
        >>> value
        'Hello, world!'
    """
    return map_(i.tap(f))

tap_to_awaitable(f)

Turn collections.abc.Awaitable-returning function into a function expecting a collections.abc.Awaitable and returning the same collections.abc.Awaitable.

Parameters:

Returns:

Example
>>> import asyncio
>>> from collections.abc import Awaitable
>>> from trcks.fp.monads import awaitable as a
>>> async def write_to_disk(output: str) -> None:
...     await asyncio.sleep(0.001)
...     print(f"Wrote '{output}' to disk.")
...
>>> write_to_disk_tapped = a.tap_to_awaitable(write_to_disk)
>>> awaitable_input = a.construct("Hello, world!")
>>> awaitable_output = write_to_disk_tapped(awaitable_input)
>>> isinstance(awaitable_output, Awaitable)
True
>>> value = asyncio.run(a.to_coroutine(awaitable_output))
Wrote 'Hello, world!' to disk.
>>> value
'Hello, world!'
Source code in src/trcks/fp/monads/awaitable.py
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
def tap_to_awaitable(
    f: Callable[[_T1], Awaitable[object]],
) -> Callable[[Awaitable[_T1]], Awaitable[_T1]]:
    """Turn [collections.abc.Awaitable][]-returning function into a function
    expecting a [collections.abc.Awaitable][] and
    returning the same [collections.abc.Awaitable][].

    Args:
        f:
            The asynchronous function to be transformed into a function
            expecting a [collections.abc.Awaitable][] and
            returning the same [collections.abc.Awaitable][].

    Returns:
        The given function transformed into a function
            expecting a [collections.abc.Awaitable][] and
            returning the same [collections.abc.Awaitable][].

    Example:
        >>> import asyncio
        >>> from collections.abc import Awaitable
        >>> from trcks.fp.monads import awaitable as a
        >>> async def write_to_disk(output: str) -> None:
        ...     await asyncio.sleep(0.001)
        ...     print(f"Wrote '{output}' to disk.")
        ...
        >>> write_to_disk_tapped = a.tap_to_awaitable(write_to_disk)
        >>> awaitable_input = a.construct("Hello, world!")
        >>> awaitable_output = write_to_disk_tapped(awaitable_input)
        >>> isinstance(awaitable_output, Awaitable)
        True
        >>> value = asyncio.run(a.to_coroutine(awaitable_output))
        Wrote 'Hello, world!' to disk.
        >>> value
        'Hello, world!'
    """

    async def bypassed_f(value: _T1) -> _T1:
        _ = await f(value)
        return value

    return map_to_awaitable(bypassed_f)

to_coroutine(awtbl) async

Turn a collections.abc.Awaitable into a collections.abc.Coroutine.

This is useful for functions that expect a coroutine (e.g. asyncio.run).

Parameters:

Returns:

Note

The type collections.abc.Awaitable is a supertype of collections.abc.Coroutine.

Example

Transform an asyncio.Future into a collections.abc.Coroutine and run it:

>>> import asyncio
>>> from trcks.fp.monads import awaitable as a
>>> asyncio.set_event_loop(asyncio.new_event_loop())
>>> future = asyncio.Future[str]()
>>> future.set_result("Hello, world!")
>>> future
<Future finished result='Hello, world!'>
>>> coro = a.to_coroutine(future)
>>> coro
<coroutine object to_coroutine at 0x...>
>>> asyncio.run(coro)
'Hello, world!'
Source code in src/trcks/fp/monads/awaitable.py
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
async def to_coroutine(awtbl: Awaitable[_T]) -> _T:
    """Turn a [collections.abc.Awaitable][] into a [collections.abc.Coroutine][].

    This is useful for functions that expect a coroutine (e.g. [asyncio.run][]).

    Args:
        awtbl: The [collections.abc.Awaitable][] to be transformed
            into a [collections.abc.Coroutine][].

    Returns:
        The given [collections.abc.Awaitable][] transformed
            into a [collections.abc.Coroutine][].

    Note:
        The type [collections.abc.Awaitable][] is
        a supertype of [collections.abc.Coroutine][].

    Example:
        Transform an [asyncio.Future][] into a [collections.abc.Coroutine][] and run it:

        >>> import asyncio
        >>> from trcks.fp.monads import awaitable as a
        >>> asyncio.set_event_loop(asyncio.new_event_loop())
        >>> future = asyncio.Future[str]()
        >>> future.set_result("Hello, world!")
        >>> future
        <Future finished result='Hello, world!'>
        >>> coro = a.to_coroutine(future)
        >>> coro
        <coroutine object to_coroutine at 0x...>
        >>> asyncio.run(coro)
        'Hello, world!'
    """
    return await awtbl