File: compose_result.py

package info (click to toggle)
python-returns 0.26.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,652 kB
  • sloc: python: 11,000; makefile: 18
file content (63 lines) | stat: -rw-r--r-- 1,894 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
from collections.abc import Callable
from typing import TypeVar

from returns.interfaces.specific.ioresult import IOResultLikeN
from returns.primitives.hkt import Kind3, Kinded, kinded
from returns.result import Result

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

_IOResultLikeKind = TypeVar('_IOResultLikeKind', bound=IOResultLikeN)


def compose_result(
    function: Callable[
        [Result[_FirstType, _SecondType]],
        Kind3[_IOResultLikeKind, _NewFirstType, _SecondType, _ThirdType],
    ],
) -> Kinded[
    Callable[
        [Kind3[_IOResultLikeKind, _FirstType, _SecondType, _ThirdType]],
        Kind3[_IOResultLikeKind, _NewFirstType, _SecondType, _ThirdType],
    ]
]:
    """
    Composes inner ``Result`` with ``IOResultLike`` returning function.

    Can be useful when you need an access to both states of the result.

    .. code:: python

      >>> from returns.io import IOResult, IOSuccess, IOFailure
      >>> from returns.pointfree import compose_result
      >>> from returns.result import Result

      >>> def modify_string(container: Result[str, str]) -> IOResult[str, str]:
      ...     return IOResult.from_result(
      ...         container.map(str.upper).alt(str.lower),
      ...     )

      >>> assert compose_result(modify_string)(
      ...     IOSuccess('success')
      ... ) == IOSuccess('SUCCESS')
      >>> assert compose_result(modify_string)(
      ...     IOFailure('FAILURE')
      ... ) == IOFailure('failure')

    """

    @kinded
    def factory(
        container: Kind3[
            _IOResultLikeKind,
            _FirstType,
            _SecondType,
            _ThirdType,
        ],
    ) -> Kind3[_IOResultLikeKind, _NewFirstType, _SecondType, _ThirdType]:
        return container.compose_result(function)

    return factory