File: lash.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,765 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 collections.abc import Callable
from typing import TypeVar

from returns.interfaces.lashable import LashableN
from returns.primitives.hkt import Kinded, KindN, kinded

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

_LashableKind = TypeVar('_LashableKind', bound=LashableN)


def lash(
    function: Callable[
        [_SecondType],
        KindN[_LashableKind, _FirstType, _UpdatedType, _ThirdType],
    ],
) -> Kinded[
    Callable[
        [KindN[_LashableKind, _FirstType, _SecondType, _ThirdType]],
        KindN[_LashableKind, _FirstType, _UpdatedType, _ThirdType],
    ]
]:
    """
    Turns function's input parameter from a regular value to a container.

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

    Similar to :func:`returns.pointfree.bind`, but works for failed containers.

    This is how it should be used:

    .. code:: python

      >>> from returns.pointfree import lash
      >>> from returns.result import Success, Failure, Result

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

      >>> assert lash(example)(Success('a')) == Success('a')
      >>> assert lash(example)(Failure(1)) == Success(2)

    Note, that this function works for all containers with ``.lash`` method.
    See :class:`returns.interfaces.lashable.Lashable` for more info.

    """

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

    return factory