File: bind_io.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 (61 lines) | stat: -rw-r--r-- 1,794 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
from __future__ import annotations

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

from returns.interfaces.specific.io import IOLikeN
from returns.primitives.hkt import Kinded, KindN, kinded

if TYPE_CHECKING:
    from returns.io import IO  # noqa: WPS433

_FirstType_contra = TypeVar('_FirstType_contra', contravariant=True)
_SecondType = TypeVar('_SecondType')
_ThirdType_contra = TypeVar('_ThirdType_contra', contravariant=True)
_UpdatedType_co = TypeVar('_UpdatedType_co', covariant=True)

_IOLikeKind = TypeVar('_IOLikeKind', bound=IOLikeN)


def bind_io(
    function: Callable[[_FirstType_contra], IO[_UpdatedType_co]],
) -> Kinded[
    Callable[
        [KindN[_IOLikeKind, _FirstType_contra, _SecondType, _ThirdType_contra]],
        KindN[_IOLikeKind, _UpdatedType_co, _SecondType, _ThirdType_contra],
    ]
]:
    """
    Composes successful container with a function that returns a container.

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

    .. code:: python

      >>> from returns.io import IOSuccess, IOFailure
      >>> from returns.io import IO
      >>> from returns.pointfree import bind_io

      >>> def returns_io(arg: int) -> IO[int]:
      ...     return IO(arg + 1)

      >>> bound = bind_io(returns_io)
      >>> assert bound(IO(1)) == IO(2)
      >>> assert bound(IOSuccess(1)) == IOSuccess(2)
      >>> assert bound(IOFailure(1)) == IOFailure(1)

    """

    @kinded
    def factory(
        container: KindN[
            _IOLikeKind, _FirstType_contra, _SecondType, _ThirdType_contra
        ],
    ) -> KindN[_IOLikeKind, _UpdatedType_co, _SecondType, _ThirdType_contra]:
        return container.bind_io(function)

    return factory