File: bind_context_result.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 (72 lines) | stat: -rw-r--r-- 2,066 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
from __future__ import annotations

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

from returns.interfaces.specific.reader_result import ReaderResultLikeN
from returns.primitives.hkt import Kinded, KindN, kinded

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

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

_ReaderResultLikeKind = TypeVar(
    '_ReaderResultLikeKind',
    bound=ReaderResultLikeN,
)


def bind_context_result(
    function: Callable[
        [_FirstType],
        ReaderResult[_UpdatedType, _SecondType, _ThirdType],
    ],
) -> Kinded[
    Callable[
        [KindN[_ReaderResultLikeKind, _FirstType, _SecondType, _ThirdType]],
        KindN[_ReaderResultLikeKind, _UpdatedType, _SecondType, _ThirdType],
    ]
]:
    """
    Composes successful container with a function that returns a container.

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

    .. code:: python

      >>> from returns.pointfree import bind_context_result
      >>> from returns.context import ReaderIOResult, ReaderResult
      >>> from returns.io import IOSuccess, IOFailure

      >>> def example(argument: int) -> ReaderResult[int, str, str]:
      ...     return ReaderResult.from_value(argument + 1)

      >>> assert bind_context_result(example)(
      ...     ReaderIOResult.from_value(1),
      ... )(...) == IOSuccess(2)
      >>> assert bind_context_result(example)(
      ...     ReaderIOResult.from_failure('a'),
      ... )(...) == IOFailure('a')

    """

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

    return factory