trcks.fp.monads.awaitable
Monadic functions for collections.abc.Awaitable.
Provides utilities for functional composition of asynchronous functions.
Examples:
>>> 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:
-
value(_T) –The value to create the collections.abc.Awaitable from.
Returns:
-
Awaitable[_T]–The collections.abc.Awaitable created from the value.
Examples:
>>> 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
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | |
map_(callable_, /, *args, **kwargs)
Turn synchronous function into a function expecting and returning collections.abc.Awaitable.
Parameters:
-
callable_(Callable[Concatenate[_T1, _P], _T2]) –The synchronous function to be transformed into a function expecting and returning a collections.abc.Awaitable.
-
*args(args, default:()) –Positional arguments to be passed to
callable_. -
**kwargs(kwargs, default:{}) –Keyword arguments to be passed to
callable_.
Returns:
-
Callable[[Awaitable[_T1]], Awaitable[_T2]]–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.
Examples:
>>> 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
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 | |
map_to_awaitable(callable_, /, *args, **kwargs)
Turn collections.abc.Awaitable-returning function into function expecting and returning collections.abc.Awaitable.
Parameters:
-
callable_(Callable[Concatenate[_T1, _P], Awaitable[_T2]]) –The collections.abc.Awaitable-returning function to be transformed into a function expecting and returning a collections.abc.Awaitable.
-
*args(args, default:()) –Positional arguments to be passed to
callable_. -
**kwargs(kwargs, default:{}) –Keyword arguments to be passed to
callable_.
Returns:
-
Callable[[Awaitable[_T1]], Awaitable[_T2]]–The given function transformed into a function expecting and returning a collections.abc.Awaitable.
Examples:
>>> 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
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 | |
map_to_awaitable_iterable(callable_, /, *args, **kwargs)
Create function that maps the value of an collections.abc.Awaitable to a trcks.AwaitableIterable and flattens the result.
Parameters:
-
callable_(Callable[Concatenate[_T1, _P], AwaitableIterable[_T2]]) –Asynchronous function to apply to the awaited value, returning a trcks.AwaitableIterable.
-
*args(args, default:()) –Positional arguments to be passed to
callable_. -
**kwargs(kwargs, default:{}) –Keyword arguments to be passed to
callable_.
Returns:
-
Callable[[Awaitable[_T1]], AwaitableTuple[_T2]]–Maps collections.abc.Awaitables to trcks.AwaitableTuples of varying length according to the given asynchronous function.
Examples:
>>> import asyncio
>>> from trcks.fp.monads import awaitable as a
>>> from trcks.fp.monads import awaitable_tuple as at
>>> async def slowly_duplicate(n: int) -> tuple[int, ...]:
... await asyncio.sleep(0.001)
... return (n, n)
...
>>> duplicate = a.map_to_awaitable_iterable(slowly_duplicate)
>>> a_tpl = duplicate(a.construct(21))
>>> asyncio.run(at.to_coroutine_tuple(a_tpl))
(21, 21)
Source code in src/trcks/fp/monads/awaitable.py
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 | |
map_to_awaitable_result(callable_, /, *args, **kwargs)
Create function that maps the value of an collections.abc.Awaitable to a trcks.AwaitableResult value.
Parameters:
-
callable_(Callable[Concatenate[_T1, _P], AwaitableResult[_F, _S]]) –Asynchronous function to apply to the awaited value, returning a trcks.AwaitableResult.
-
*args(args, default:()) –Positional arguments to be passed to
callable_. -
**kwargs(kwargs, default:{}) –Keyword arguments to be passed to
callable_.
Returns:
-
Callable[[Awaitable[_T1]], AwaitableResult[_F, _S]]–Maps collections.abc.Awaitables to trcks.AwaitableResults according to the given asynchronous function.
Examples:
>>> import asyncio
>>> from trcks import Result
>>> from trcks.fp.monads import awaitable as a
>>> from trcks.fp.monads import awaitable_result as ar
>>> async def slowly_assert_non_negative(
... x: float,
... ) -> Result[str, float]:
... await asyncio.sleep(0.001)
... if x < 0:
... return "failure", "negative value"
... return "success", x
...
>>> assert_non_negative = a.map_to_awaitable_result(
... slowly_assert_non_negative
... )
>>> a_rslt = assert_non_negative(a.construct(42.0))
>>> asyncio.run(ar.to_coroutine_result(a_rslt))
('success', 42.0)
Source code in src/trcks/fp/monads/awaitable.py
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 | |
map_to_awaitable_result_iterable(callable_, /, *args, **kwargs)
Create function that maps the value of an collections.abc.Awaitable to a trcks.AwaitableResultIterable and flattens the result.
Parameters:
-
callable_(Callable[Concatenate[_T1, _P], AwaitableResultIterable[_F, _S]]) –Asynchronous function to apply to the awaited value, returning a trcks.AwaitableResultIterable.
-
*args(args, default:()) –Positional arguments to be passed to
callable_. -
**kwargs(kwargs, default:{}) –Keyword arguments to be passed to
callable_.
Returns:
-
Callable[[Awaitable[_T1]], AwaitableResultTuple[_F, _S]]–Maps collections.abc.Awaitables to trcks.AwaitableResultTuples with
- the trcks.Failure returned by the function, or
- a trcks.SuccessTuple containing the elements of the trcks.SuccessIterable returned by the function.
Examples:
>>> import asyncio
>>> from trcks import AwaitableResultTuple
>>> from trcks.fp.monads import awaitable as a
>>> from trcks.fp.monads import awaitable_result_tuple as art
>>> async def validate(x: float) -> AwaitableResultTuple[str, float]:
... await asyncio.sleep(0.001)
... if x < 0:
... return "failure", "negative value"
... return "success", (x, x * 2)
...
>>> validate_value = a.map_to_awaitable_result_iterable(validate)
>>> a_r_tpl = validate_value(a.construct(5.0))
>>> asyncio.run(art.to_coroutine_result_tuple(a_r_tpl))
('success', (5.0, 10.0))
Source code in src/trcks/fp/monads/awaitable.py
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 | |
map_to_awaitable_result_tuple(callable_, /, *args, **kwargs)
Deprecated alias for trcks.fp.monads.awaitable.map_to_awaitable_result_iterable.
Source code in src/trcks/fp/monads/awaitable.py
248 249 250 251 252 253 254 255 256 257 258 259 260 | |
map_to_awaitable_tuple(callable_, /, *args, **kwargs)
Deprecated alias for trcks.fp.monads.awaitable.map_to_awaitable_iterable.
Source code in src/trcks/fp/monads/awaitable.py
263 264 265 266 267 268 269 270 271 | |
map_to_iterable(callable_, /, *args, **kwargs)
Create function that maps the value of an collections.abc.Awaitable to a collections.abc.Iterable and flattens the result.
Parameters:
-
callable_(Callable[Concatenate[_T1, _P], Iterable[_T2]]) –Synchronous function to apply to the awaited value, returning a collections.abc.Iterable.
-
*args(args, default:()) –Positional arguments to be passed to
callable_. -
**kwargs(kwargs, default:{}) –Keyword arguments to be passed to
callable_.
Returns:
-
Callable[[Awaitable[_T1]], AwaitableTuple[_T2]]–Maps collections.abc.Awaitables to trcks.AwaitableTuples of varying length according to the given function.
Examples:
>>> import asyncio
>>> from trcks.fp.monads import awaitable as a
>>> from trcks.fp.monads import awaitable_tuple as at
>>> duplicate_with_negative = a.map_to_iterable(lambda n: (n, -n))
>>> a_tpl = duplicate_with_negative(a.construct(3))
>>> asyncio.run(at.to_coroutine_tuple(a_tpl))
(3, -3)
Source code in src/trcks/fp/monads/awaitable.py
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 | |
map_to_result(callable_, /, *args, **kwargs)
Create function that maps the value of an collections.abc.Awaitable to a trcks.Result value.
Parameters:
-
callable_(Callable[Concatenate[_T1, _P], Result[_F, _S]]) –Synchronous function to apply to the awaited value, returning a trcks.Result.
-
*args(args, default:()) –Positional arguments to be passed to
callable_. -
**kwargs(kwargs, default:{}) –Keyword arguments to be passed to
callable_.
Returns:
-
Callable[[Awaitable[_T1]], AwaitableResult[_F, _S]]–Maps collections.abc.Awaitables to trcks.AwaitableResults according to the given function.
Examples:
>>> import asyncio
>>> from trcks.fp.monads import awaitable as a
>>> from trcks.fp.monads import awaitable_result as ar
>>> assert_non_negative = a.map_to_result(
... lambda n: (
... ("success", n) if n >= 0 else ("failure", "negative value")
... )
... )
>>> a_rslt = assert_non_negative(a.construct(-1))
>>> asyncio.run(ar.to_coroutine_result(a_rslt))
('failure', 'negative value')
Source code in src/trcks/fp/monads/awaitable.py
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 | |
map_to_result_iterable(callable_, /, *args, **kwargs)
Create function that maps the value of an collections.abc.Awaitable to a trcks.ResultIterable and flattens the result.
Parameters:
-
callable_(Callable[Concatenate[_T1, _P], ResultIterable[_F, _S]]) –Synchronous function to apply to the awaited value, returning a trcks.ResultIterable.
-
*args(args, default:()) –Positional arguments to be passed to
callable_. -
**kwargs(kwargs, default:{}) –Keyword arguments to be passed to
callable_.
Returns:
-
Callable[[Awaitable[_T1]], AwaitableResultTuple[_F, _S]]–Maps collections.abc.Awaitables to trcks.AwaitableResultTuples with
- the trcks.Failure returned by the function, or
- a trcks.SuccessTuple containing the elements of the trcks.SuccessIterable returned by the function.
Examples:
>>> import asyncio
>>> from trcks import ResultTuple
>>> from trcks.fp.monads import awaitable as a
>>> from trcks.fp.monads import awaitable_result_tuple as art
>>> def validate(x: float) -> ResultTuple[str, float]:
... if x < 0:
... return "failure", "negative value"
... return "success", (x, x * 2)
...
>>> validate_value = a.map_to_result_iterable(validate)
>>> a_r_tpl = validate_value(a.construct(5.0))
>>> asyncio.run(art.to_coroutine_result_tuple(a_r_tpl))
('success', (5.0, 10.0))
Source code in src/trcks/fp/monads/awaitable.py
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 | |
map_to_result_tuple(callable_, /, *args, **kwargs)
Deprecated alias for trcks.fp.monads.awaitable.map_to_result_iterable.
Source code in src/trcks/fp/monads/awaitable.py
404 405 406 407 408 409 410 411 412 | |
map_to_tuple(callable_, /, *args, **kwargs)
Deprecated alias for trcks.fp.monads.awaitable.map_to_iterable.
Source code in src/trcks/fp/monads/awaitable.py
415 416 417 418 419 420 421 422 423 | |
tap(callable_, /, *args, **kwargs)
Turn synchronous function into a function expecting a collections.abc.Awaitable and returning the same collections.abc.Awaitable.
Parameters:
-
callable_(Callable[Concatenate[_T1, _P], object]) –The synchronous function to be transformed into a function expecting a collections.abc.Awaitable and returning the same collections.abc.Awaitable.
-
*args(args, default:()) –Positional arguments to be passed to
callable_. -
**kwargs(kwargs, default:{}) –Keyword arguments to be passed to
callable_.
Returns:
-
Callable[[Awaitable[_T1]], Awaitable[_T1]]–The given function transformed into a function expecting a collections.abc.Awaitable and returning the same collections.abc.Awaitable.
Examples:
>>> 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
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 | |
tap_to_awaitable(callable_, /, *args, **kwargs)
Turn collections.abc.Awaitable-returning function into a function expecting a collections.abc.Awaitable and returning the same collections.abc.Awaitable.
Parameters:
-
callable_(Callable[Concatenate[_T1, _P], Awaitable[object]]) –The asynchronous function to be transformed into a function expecting a collections.abc.Awaitable and returning the same collections.abc.Awaitable.
-
*args(args, default:()) –Positional arguments to be passed to
callable_. -
**kwargs(kwargs, default:{}) –Keyword arguments to be passed to
callable_.
Returns:
-
Callable[[Awaitable[_T1]], Awaitable[_T1]]–The given function transformed into a function expecting a collections.abc.Awaitable and returning the same collections.abc.Awaitable.
Examples:
>>> 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
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 | |
tap_to_awaitable_iterable(callable_, /, *args, **kwargs)
Create function that applies an asynchronous side effect with return type trcks.AwaitableIterable to the value of an collections.abc.Awaitable.
Parameters:
-
callable_(Callable[Concatenate[_T1, _P], AwaitableIterable[object]]) –Asynchronous side effect to apply to the awaited value, returning a trcks.AwaitableIterable.
-
*args(args, default:()) –Positional arguments to be passed to
callable_. -
**kwargs(kwargs, default:{}) –Keyword arguments to be passed to
callable_.
Returns:
-
Callable[[Awaitable[_T1]], AwaitableTuple[_T1]]–Maps collections.abc.Awaitables to trcks.AwaitableTuples with the original awaited value repeated once per element in the side effect output.
Examples:
>>> import asyncio
>>> from trcks.fp.monads import awaitable as a
>>> from trcks.fp.monads import awaitable_tuple as at
>>> async def slowly_duplicate_with_log(n: int) -> tuple[int, ...]:
... await asyncio.sleep(0.001)
... print(f"Processing: {n}")
... return (n, n)
...
>>> process_and_duplicate = a.tap_to_awaitable_iterable(
... slowly_duplicate_with_log
... )
>>> a_tpl = process_and_duplicate(a.construct(21))
>>> asyncio.run(at.to_coroutine_tuple(a_tpl))
Processing: 21
(21, 21)
Source code in src/trcks/fp/monads/awaitable.py
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 | |
tap_to_awaitable_result(callable_, /, *args, **kwargs)
Create function that applies an asynchronous side effect with return type trcks.AwaitableResult to the value of an collections.abc.Awaitable.
Parameters:
-
callable_(Callable[Concatenate[_T1, _P], AwaitableResult[_F, object]]) –Asynchronous side effect to apply to the awaited value, returning a trcks.AwaitableResult.
-
*args(args, default:()) –Positional arguments to be passed to
callable_. -
**kwargs(kwargs, default:{}) –Keyword arguments to be passed to
callable_.
Returns:
-
Callable[[Awaitable[_T1]], AwaitableResult[_F, _T1]]–Maps collections.abc.Awaitables to trcks.AwaitableResults with
- the returned trcks.Failure if the applied side effect returns a trcks.Failure, or
- the original awaited value as trcks.AwaitableSuccess if the applied side effect returns trcks.Success.
Examples:
>>> import asyncio
>>> from typing import Literal
>>> from trcks import Result
>>> from trcks.fp.monads import awaitable as a
>>> from trcks.fp.monads import awaitable_result as ar
>>> WriteErrorLiteral = Literal["write error"]
>>> async def write_to_disk(s: str, path: str) -> Result[
... WriteErrorLiteral, None
... ]:
... if path != "output.txt":
... return "failure", "write error"
... await asyncio.sleep(0.001)
... print(f"Wrote '{s}' to file {path}.")
... return "success", None
...
>>> tap_write_to_error_file = a.tap_to_awaitable_result(
... write_to_disk,
... "error.txt",
... )
>>> a_rslt_1 = tap_write_to_error_file(a.construct("Hello, world!"))
>>> asyncio.run(ar.to_coroutine_result(a_rslt_1))
('failure', 'write error')
>>> tap_write_to_output_file = a.tap_to_awaitable_result(
... write_to_disk,
... "output.txt",
... )
>>> a_rslt_2 = tap_write_to_output_file(a.construct("Hello, world!"))
>>> asyncio.run(ar.to_coroutine_result(a_rslt_2))
Wrote 'Hello, world!' to file output.txt.
('success', 'Hello, world!')
Source code in src/trcks/fp/monads/awaitable.py
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 | |
tap_to_awaitable_result_iterable(callable_, /, *args, **kwargs)
Create function that applies an asynchronous side effect with return type trcks.AwaitableResultIterable to the value of an collections.abc.Awaitable.
Parameters:
-
callable_(Callable[Concatenate[_T1, _P], AwaitableResultIterable[_F, object]]) –Asynchronous side effect to apply to the awaited value, returning a trcks.AwaitableResultIterable.
-
*args(args, default:()) –Positional arguments to be passed to
callable_. -
**kwargs(kwargs, default:{}) –Keyword arguments to be passed to
callable_.
Returns:
-
Callable[[Awaitable[_T1]], AwaitableResultTuple[_F, _T1]]–Maps collections.abc.Awaitables to trcks.AwaitableResultTuples with
- the returned trcks.Failure if the applied side effect returns a trcks.Failure, or
- the original awaited value repeated once per element in the side effect output if the applied side effect returns trcks.SuccessIterable.
Examples:
>>> import asyncio
>>> from trcks import AwaitableResultTuple
>>> from trcks.fp.monads import awaitable as a
>>> from trcks.fp.monads import awaitable_result_tuple as art
>>> async def write_twice(s: str) -> AwaitableResultTuple[str, None]:
... await asyncio.sleep(0.001)
... print(f"Wrote '{s}' twice.")
... return "success", (None, None)
...
>>> write_twice_tapped = a.tap_to_awaitable_result_iterable(write_twice)
>>> a_r_tpl = write_twice_tapped(a.construct("Hello, world!"))
>>> asyncio.run(art.to_coroutine_result_tuple(a_r_tpl))
Wrote 'Hello, world!' twice.
('success', ('Hello, world!', 'Hello, world!'))
Source code in src/trcks/fp/monads/awaitable.py
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 | |
tap_to_awaitable_result_tuple(callable_, /, *args, **kwargs)
Deprecated alias for trcks.fp.monads.awaitable.tap_to_awaitable_result_iterable.
Source code in src/trcks/fp/monads/awaitable.py
595 596 597 598 599 600 601 602 603 604 605 606 607 | |
tap_to_awaitable_tuple(callable_, /, *args, **kwargs)
Deprecated alias for trcks.fp.monads.awaitable.tap_to_awaitable_iterable.
Source code in src/trcks/fp/monads/awaitable.py
610 611 612 613 614 615 616 617 618 | |
tap_to_iterable(callable_, /, *args, **kwargs)
Create function that applies a synchronous side effect with return type collections.abc.Iterable to the value of an collections.abc.Awaitable.
Parameters:
-
callable_(Callable[Concatenate[_T1, _P], Iterable[object]]) –Synchronous side effect to apply to the awaited value, returning a collections.abc.Iterable.
-
*args(args, default:()) –Positional arguments to be passed to
callable_. -
**kwargs(kwargs, default:{}) –Keyword arguments to be passed to
callable_.
Returns:
-
Callable[[Awaitable[_T1]], AwaitableTuple[_T1]]–Maps collections.abc.Awaitables to trcks.AwaitableTuples with the original awaited value repeated once per element in the side effect output.
Examples:
>>> import asyncio
>>> from trcks.fp.monads import awaitable as a
>>> from trcks.fp.monads import awaitable_tuple as at
>>> def duplicate_with_log(n: int) -> tuple[int, ...]:
... print(f"Processing: {n}")
... return (n, n)
...
>>> process_and_duplicate = a.tap_to_iterable(duplicate_with_log)
>>> a_tpl = process_and_duplicate(a.construct(42))
>>> asyncio.run(at.to_coroutine_tuple(a_tpl))
Processing: 42
(42, 42)
Source code in src/trcks/fp/monads/awaitable.py
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 | |
tap_to_result(callable_, /, *args, **kwargs)
Create function that applies a synchronous side effect with return type trcks.Result to the value of an collections.abc.Awaitable.
Parameters:
-
callable_(Callable[Concatenate[_T1, _P], Result[_F, object]]) –Synchronous side effect to apply to the awaited value, returning a trcks.Result.
-
*args(args, default:()) –Positional arguments to be passed to
callable_. -
**kwargs(kwargs, default:{}) –Keyword arguments to be passed to
callable_.
Returns:
-
Callable[[Awaitable[_T1]], AwaitableResult[_F, _T1]]–Maps collections.abc.Awaitables to trcks.AwaitableResults with
- the returned trcks.Failure if the applied side effect returns a trcks.Failure, or
- the original awaited value as trcks.AwaitableSuccess if the applied side effect returns trcks.Success.
Examples:
>>> import asyncio
>>> from trcks import Result
>>> from trcks.fp.monads import awaitable as a
>>> from trcks.fp.monads import awaitable_result as ar
>>> def print_positive_float(x: float) -> Result[str, None]:
... if x <= 0:
... return "failure", "not positive"
... return "success", print(f"Positive float: {x}")
...
>>> tap_positive_float = a.tap_to_result(print_positive_float)
>>> a_rslt_1 = tap_positive_float(a.construct(-2.3))
>>> asyncio.run(ar.to_coroutine_result(a_rslt_1))
('failure', 'not positive')
>>> a_rslt_2 = tap_positive_float(a.construct(3.5))
>>> asyncio.run(ar.to_coroutine_result(a_rslt_2))
Positive float: 3.5
('success', 3.5)
Source code in src/trcks/fp/monads/awaitable.py
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 | |
tap_to_result_iterable(callable_, /, *args, **kwargs)
Create function that applies a synchronous side effect with return type trcks.ResultIterable to the value of an collections.abc.Awaitable.
Parameters:
-
callable_(Callable[Concatenate[_T1, _P], ResultIterable[_F, object]]) –Synchronous side effect to apply to the awaited value, returning a trcks.ResultIterable.
-
*args(args, default:()) –Positional arguments to be passed to
callable_. -
**kwargs(kwargs, default:{}) –Keyword arguments to be passed to
callable_.
Returns:
-
Callable[[Awaitable[_T1]], AwaitableResultTuple[_F, _T1]]–Maps collections.abc.Awaitables to trcks.AwaitableResultTuples with
- the returned trcks.Failure if the applied side effect returns a trcks.Failure, or
- the original awaited value repeated once per element in the side effect output if the applied side effect returns trcks.SuccessIterable.
Examples:
>>> import asyncio
>>> from trcks import ResultTuple
>>> from trcks.fp.monads import awaitable as a
>>> from trcks.fp.monads import awaitable_result_tuple as art
>>> def write_twice(s: str) -> ResultTuple[str, None]:
... print(f"Wrote '{s}' twice.")
... return "success", (None, None)
...
>>> write_twice_tapped = a.tap_to_result_iterable(write_twice)
>>> a_r_tpl = write_twice_tapped(a.construct("Hello, world!"))
>>> asyncio.run(art.to_coroutine_result_tuple(a_r_tpl))
Wrote 'Hello, world!' twice.
('success', ('Hello, world!', 'Hello, world!'))
Source code in src/trcks/fp/monads/awaitable.py
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 | |
tap_to_result_tuple(callable_, /, *args, **kwargs)
Deprecated alias for trcks.fp.monads.awaitable.tap_to_result_iterable.
Source code in src/trcks/fp/monads/awaitable.py
772 773 774 775 776 777 778 779 780 | |
tap_to_tuple(callable_, /, *args, **kwargs)
Deprecated alias for trcks.fp.monads.awaitable.tap_to_iterable.
Source code in src/trcks/fp/monads/awaitable.py
783 784 785 786 787 788 789 790 791 | |
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 in Python 3.13 and older).
Parameters:
-
awtbl(Awaitable[_T]) –The collections.abc.Awaitable to be transformed into a collections.abc.Coroutine.
Returns:
-
_T–The given collections.abc.Awaitable transformed into a collections.abc.Coroutine.
Note
The type collections.abc.Awaitable is a supertype of collections.abc.Coroutine.
Examples:
Transform an asyncio.Future into a collections.abc.Coroutine and run it:
>>> import asyncio
>>> from trcks.fp.monads import awaitable as a
>>> loop = asyncio.new_event_loop()
>>> future: asyncio.Future[str] = loop.create_future()
>>> future.set_result("Hello, world!")
>>> future
<Future finished result='Hello, world!'>
>>> coro = a.to_coroutine(future)
>>> coro
<coroutine object to_coroutine at 0x...>
>>> loop.run_until_complete(coro)
'Hello, world!'
>>> loop.close()
Source code in src/trcks/fp/_monads/awaitable.py
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 | |