File: bind_context_ioresult.py

package info (click to toggle)
python-returns 0.26.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,652 kB
  • sloc: python: 11,000; makefile: 18
file content (78 lines) | stat: -rw-r--r-- 2,348 bytes parent folder | download | duplicates (2)
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
from __future__ import annotations

from collections.abc import Callable
from typing import TYPE_CHECKING, TypeVar

from returns.interfaces.specific.reader_ioresult import ReaderIOResultLikeN
from returns.primitives.hkt import Kinded, KindN, kinded

if TYPE_CHECKING:
    from returns.context import ReaderIOResult  # noqa: WPS433

_FirstType = TypeVar('_FirstType')
_SecondType = TypeVar('_SecondType')
_ThirdType = TypeVar('_ThirdType')
_UpdatedType = TypeVar('_UpdatedType')

_ReaderIOResultLikeKind = TypeVar(
    '_ReaderIOResultLikeKind',
    bound=ReaderIOResultLikeN,
)


def bind_context_ioresult(
    function: Callable[
        [_FirstType],
        ReaderIOResult[_UpdatedType, _SecondType, _ThirdType],
    ],
) -> Kinded[
    Callable[
        [KindN[_ReaderIOResultLikeKind, _FirstType, _SecondType, _ThirdType]],
        KindN[_ReaderIOResultLikeKind, _UpdatedType, _SecondType, _ThirdType],
    ]
]:
    """
    Lifts function from ``RequiresContextIOResult`` for better composition.

    In other words, it modifies the function's
    signature from:
    ``a -> RequiresContextIOResult[env, b, c]``
    to:
    ``Container[env, a, c]`` -> ``Container[env, b, c]``

    .. code:: python

      >>> import anyio
      >>> from returns.context import (
      ...     RequiresContextFutureResult,
      ...     RequiresContextIOResult,
      ... )
      >>> from returns.io import IOSuccess, IOFailure
      >>> from returns.pointfree import bind_context_ioresult

      >>> def function(arg: int) -> RequiresContextIOResult[str, int, str]:
      ...     return RequiresContextIOResult(
      ...         lambda deps: IOSuccess(len(deps) + arg),
      ...     )

      >>> assert anyio.run(bind_context_ioresult(function)(
      ...     RequiresContextFutureResult.from_value(2),
      ... )('abc').awaitable) == IOSuccess(5)
      >>> assert anyio.run(bind_context_ioresult(function)(
      ...     RequiresContextFutureResult.from_failure(0),
      ... )('abc').awaitable) == IOFailure(0)

    """

    @kinded
    def factory(
        container: KindN[
            _ReaderIOResultLikeKind,
            _FirstType,
            _SecondType,
            _ThirdType,
        ],
    ) -> KindN[_ReaderIOResultLikeKind, _UpdatedType, _SecondType, _ThirdType]:
        return container.bind_context_ioresult(function)

    return factory