示例#1
0
 def traverse(gap: Applicative[G], fa: Kind1[Option, A],\
              f: Func1[A, Kind1[G, B]]) -> Kind2[G, Option, B]:
     if dekind(fa).is_empty():
         return cast(Kind2[G, Option, B], gap.pure(Nothing()))
     else:
         ff: Func1[B, Option[B]] = Some
         return gap.map(f(dekind(fa).get), ff)
示例#2
0
文件: io.py 项目: nurumaik/returns
    def from_iterable(
        cls,
        inner_value: Iterable[Kind2['IOResult', _ValueType, _ErrorType]],
    ) -> 'IOResult[Sequence[_ValueType], _ErrorType]':
        """
        Transforms an iterable of ``IOResult`` containers into a single one.

        .. code:: python

          >>> from returns.io import IOResult, IOSuccess, IOFailure

          >>> assert IOResult.from_iterable([
          ...    IOSuccess(1),
          ...    IOSuccess(2),
          ... ]) == IOSuccess((1, 2))

          >>> assert IOResult.from_iterable([
          ...     IOSuccess(1),
          ...     IOFailure('a'),
          ... ]) == IOFailure('a')

          >>> assert IOResult.from_iterable([
          ...     IOFailure('a'),
          ...     IOSuccess(1),
          ... ]) == IOFailure('a')

        """
        return dekind(iterable_kind(cls, inner_value))
    def apply(
        self,
        container: Kind3['RequiresContextFutureResult',
                         Callable[[_ValueType],
                                  _NewValueType], _ErrorType, _EnvType, ],
    ) -> 'RequiresContextFutureResult[_NewValueType, _ErrorType, _EnvType]':
        """
        Calls a wrapped function in a container on this container.

        .. code:: python

          >>> import anyio
          >>> from returns.context import RequiresContextFutureResult
          >>> from returns.io import IOSuccess, IOFailure

          >>> def transform(arg: str) -> str:
          ...     return arg + 'b'

          >>> assert anyio.run(
          ...    RequiresContextFutureResult.from_value('a').apply(
          ...        RequiresContextFutureResult.from_value(transform),
          ...    ),
          ...    RequiresContextFutureResult.empty,
          ... ) == IOSuccess('ab')

          >>> assert anyio.run(
          ...    RequiresContextFutureResult.from_failure('a').apply(
          ...        RequiresContextFutureResult.from_value(transform),
          ...    ),
          ...    RequiresContextFutureResult.empty,
          ... ) == IOFailure('a')

        """
        return RequiresContextFutureResult(
            lambda deps: self(deps).apply(dekind(container)(deps)), )
示例#4
0
    def compose_result(
        self,
        function: Callable[[Result[_ValueType, _ErrorType]],
                           Kind3[RequiresContextIOResult, _NewValueType,
                                 _ErrorType, _EnvType, ], ],
    ) -> RequiresContextIOResult[_NewValueType, _ErrorType, _EnvType]:
        """
        Composes inner ``Result`` with ``ReaderIOResult`` returning function.

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

        .. code:: python

          >>> from returns.context import ReaderIOResult, NoDeps
          >>> from returns.io import IOSuccess, IOFailure
          >>> from returns.result import Result

          >>> def count(
          ...    container: Result[int, int],
          ... ) -> ReaderIOResult[int, int, NoDeps]:
          ...     return ReaderIOResult.from_result(
          ...         container.map(lambda x: x + 1).alt(abs),
          ...     )

          >>> success = ReaderIOResult.from_value(1)
          >>> failure = ReaderIOResult.from_failure(-1)
          >>> assert success.compose_result(count)(...) == IOSuccess(2)
          >>> assert failure.compose_result(count)(...) == IOFailure(1)

        """
        return RequiresContextIOResult(
            lambda deps: dekind(
                function(self(deps)._inner_value),  # noqa: WPS437
            )(deps), )
示例#5
0
    def bind(
        self,
        function: Callable[[_ReturnType], Kind2['RequiresContext',
                                                _NewReturnType, _EnvType], ],
    ) -> RequiresContext[_NewReturnType, _EnvType]:
        """
        Composes a container with a function returning another container.

        This is useful when you do several computations that rely on the
        same context.

        .. code:: python

          >>> from returns.context import RequiresContext

          >>> def first(lg: bool) -> RequiresContext[int, float]:
          ...     # `deps` has `float` type here:
          ...     return RequiresContext(
          ...         lambda deps: deps if lg else -deps,
          ...     )

          >>> def second(number: int) -> RequiresContext[str, float]:
          ...     # `deps` has `float` type here:
          ...     return RequiresContext(
          ...         lambda deps: '>=' if number >= deps else '<',
          ...     )

          >>> assert first(True).bind(second)(1) == '>='
          >>> assert first(False).bind(second)(2) == '<'

        """
        return RequiresContext(lambda deps: dekind(function(self(deps)))(deps))
示例#6
0
文件: io.py 项目: novikovfred/returns
    def compose_result(
        self,
        function: Callable[[Result[_ValueType, _ErrorType]],
                           Kind2['IOResult', _NewValueType, _ErrorType], ],
    ) -> 'IOResult[_NewValueType, _ErrorType]':
        """
        Composes inner ``Result`` with ``IOResult`` 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.result import Result

          >>> def count(container: Result[int, int]) -> IOResult[int, int]:
          ...     return IOResult.from_result(
          ...         container.map(lambda x: x + 1).alt(abs),
          ...     )

          >>> assert IOSuccess(1).compose_result(count) == IOSuccess(2)
          >>> assert IOFailure(-1).compose_result(count) == IOFailure(1)

        """
        return dekind(function(self._inner_value))
示例#7
0
 def bind(
     self,
     function: Callable[[_FirstType], Kind2['Pair', _NewFirstType,
                                            _SecondType], ],
 ) -> 'Pair[_NewFirstType, _SecondType]':
     """Changes the first type with a function returning another Pair."""
     return dekind(function(self._inner_value[0]))
示例#8
0
    def apply(
        self,
        container: Kind1['IO', Callable[[_ValueType], _NewValueType]],
    ) -> 'IO[_NewValueType]':
        """
        Calls a wrapped function in a container on this container.

        .. code:: python

          >>> from returns.io import IO
          >>> assert IO('a').apply(IO(lambda inner: inner + 'b')) == IO('ab')

        Or more complex example that shows how we can work
        with regular functions and multiple ``IO`` arguments:

        .. code:: python

          >>> from returns.curry import curry

          >>> @curry
          ... def appliable(first: str, second: str) -> str:
          ...      return first + second

          >>> assert IO('b').apply(IO('a').apply(IO(appliable))) == IO('ab')

        """
        return self.map(dekind(container)._inner_value)  # noqa: WPS437
示例#9
0
    def apply(
        self,
        container: Kind3['RequiresContextResult', Callable[[_ValueType],
                                                           _NewValueType],
                         _ErrorType, _EnvType, ],
    ) -> 'RequiresContextResult[_NewValueType, _ErrorType, _EnvType]':
        """
        Calls a wrapped function in a container on this container.

        .. code:: python

          >>> from returns.context import RequiresContextResult
          >>> from returns.result import Success, Failure, Result

          >>> def transform(arg: str) -> str:
          ...     return arg + 'b'

          >>> assert RequiresContextResult.from_value('a').apply(
          ...    RequiresContextResult.from_value(transform),
          ... )(...) == Success('ab')

          >>> assert RequiresContextResult.from_failure('a').apply(
          ...    RequiresContextResult.from_value(transform),
          ... )(...) == Failure('a')

          >>> assert isinstance(RequiresContextResult.from_value('a').apply(
          ...    RequiresContextResult.from_failure(transform),
          ... )(...), Result.failure_type) is True

        """
        return RequiresContextResult(
            lambda deps: self(deps).apply(dekind(container)(deps)), )
示例#10
0
    def from_iterable(
        cls,
        inner_value: Iterable[Kind3['RequiresContextResult', _ValueType,
                                    _ErrorType, _EnvType, ], ],
    ) -> 'RequiresContextResult[Sequence[_ValueType], _ErrorType, _EnvType]':
        """
        Transforms an iterable of ``RequiresContextResult`` containers.

        Returns a single container with multiple elements inside.

        .. code:: python

          >>> from returns.context import RequiresContextResult
          >>> from returns.result import Success, Failure

          >>> assert RequiresContextResult.from_iterable([
          ...    RequiresContextResult.from_value(1),
          ...    RequiresContextResult.from_value(2),
          ... ])(...) == Success((1, 2))

          >>> assert RequiresContextResult.from_iterable([
          ...    RequiresContextResult.from_value(1),
          ...    RequiresContextResult.from_failure('a'),
          ... ])(...) == Failure('a')

          >>> assert RequiresContextResult.from_iterable([
          ...    RequiresContextResult.from_failure('a'),
          ...    RequiresContextResult.from_value(1),
          ... ])(...) == Failure('a')

        """
        return dekind(iterable_kind(cls, inner_value))
示例#11
0
    def from_iterable(
        cls,
        inner_value: Iterable[Kind2['FutureResult', _ValueType, _ErrorType]],
    ) -> 'FutureResult[Sequence[_ValueType], _ErrorType]':
        """
        Transforms an iterable of ``FutureResult`` containers.

        Returns a single container with multiple elements inside.

        .. code:: python

          >>> import anyio
          >>> from returns.future import FutureResult
          >>> from returns.io import IOSuccess, IOFailure

          >>> all_success = FutureResult.from_iterable([
          ...    FutureResult.from_value(1),
          ...    FutureResult.from_value(2),
          ... ])
          >>> assert anyio.run(all_success.awaitable) == IOSuccess((1, 2))

          >>> mixed = FutureResult.from_iterable([
          ...     FutureResult.from_value(1),
          ...     FutureResult.from_failure('a'),
          ... ])
          >>> assert anyio.run(mixed.awaitable) == IOFailure('a')

          >>> mixed = FutureResult.from_iterable([
          ...     FutureResult.from_failure('a'),
          ...     FutureResult.from_value(1),
          ... ])
          >>> assert anyio.run(mixed.awaitable) == IOFailure('a')

        """
        return dekind(iterable_kind(cls, inner_value))
示例#12
0
    def from_iterable(
        cls,
        inner_value: Iterable[Kind1['Maybe', _ValueType]],
    ) -> 'Maybe[Sequence[_ValueType]]':
        """
        Transforms an iterable of ``Maybe`` containers into a single container.

        .. code:: python

          >>> from returns.maybe import Maybe, Some, Nothing

          >>> assert Maybe.from_iterable([
          ...    Some(1),
          ...    Some(2),
          ... ]) == Some((1, 2))

          >>> assert Maybe.from_iterable([
          ...     Some(1),
          ...     Nothing,
          ... ]) == Nothing

          >>> assert Maybe.from_iterable([
          ...     Nothing,
          ...     Some(1),
          ... ]) == Nothing

        """
        return dekind(iterable_kind(cls, inner_value))
示例#13
0
async def async_bind_async(
    function: Callable[[_ValueType], Awaitable[Kind1['Future',
                                                     _NewValueType]], ],
    inner_value: Awaitable[_ValueType],
) -> _NewValueType:
    """Async binds a coroutine with container over a value."""
    inner_io = dekind(await function(await inner_value))._inner_value
    return await inner_io
示例#14
0
 def lash(
     self,
     function: Callable[
         [_SecondType],
         Kind2['Pair', _FirstType, _NewSecondType],
     ],
 ) -> 'Pair[_FirstType, _NewSecondType]':
     return dekind(function(self._inner_value[1]))
示例#15
0
async def async_compose_result(
    function: Callable[[Result[_ValueType, _ErrorType]],
                       Kind3['RequiresContextFutureResult', _NewValueType,
                             _ErrorType, _EnvType, ], ],
    container: 'RequiresContextFutureResult[_ValueType, _ErrorType, _EnvType]',
    deps: _EnvType,
) -> Result[_NewValueType, _ErrorType]:
    """Async composes ``Result`` based function."""
    new_container = dekind(function((await container(deps))._inner_value))
    return (await new_container(deps))._inner_value
示例#16
0
    def bind(
        self,
        function: Callable[[_FirstType], Kind2['Pair', _NewFirstType,
                                               _SecondType], ],
    ) -> 'Pair[_NewFirstType, _SecondType]':
        """
        Changes the first type with a function returning another ``Pair``.

        >>> def bindable(first: int) -> Pair[str, str]:
        ...     return Pair((str(first), ''))

        >>> assert Pair((1, 'b')).bind(bindable) == Pair(('1', ''))

        """
        return dekind(function(self._inner_value[0]))
示例#17
0
    def lash(
        self,
        function: Callable[[_SecondType], Kind2['Pair', _FirstType,
                                                _NewSecondType], ],
    ) -> 'Pair[_FirstType, _NewSecondType]':
        """
        Changes the second type with a function returning ``Pair``.

        >>> def lashable(second: int) -> Pair[str, str]:
        ...     return Pair(('', str(second)))

        >>> assert Pair(('a', 2)).lash(lashable) == Pair(('', '2'))

        """
        return dekind(function(self._inner_value[1]))
示例#18
0
    def pair(
        self,
        function: Callable[[_FirstType, _SecondType],
                           Kind2['Pair', _NewFirstType, _NewSecondType], ],
    ) -> 'Pair[_NewFirstType, _NewSecondType]':
        """
        Creates a new ``Pair`` from an existing one via a passed function.

        >>> def min_max(first: int, second: int) -> Pair[int, int]:
        ...     return Pair((min(first, second), max(first, second)))

        >>> assert Pair((2, 1)).pair(min_max) == Pair((1, 2))
        >>> assert Pair((1, 2)).pair(min_max) == Pair((1, 2))

        """
        return dekind(function(self._inner_value[0], self._inner_value[1]))
    def bind(
        self,
        function: Callable[
            [_ValueType],
            Kind3[
                RequiresContextFutureResult,
                _NewValueType,
                _ErrorType,
                _EnvType,
            ],
        ],
    ) -> RequiresContextFutureResult[_NewValueType, _ErrorType, _EnvType]:
        """
        Composes this container with a function returning the same type.

        .. code:: python

          >>> import anyio
          >>> from returns.context import RequiresContextFutureResult
          >>> from returns.future import FutureResult
          >>> from returns.io import IOSuccess, IOFailure

          >>> def function(
          ...     number: int,
          ... ) -> RequiresContextFutureResult[str, int, int]:
          ...     # `deps` has `int` type here:
          ...     return RequiresContextFutureResult(
          ...         lambda deps: FutureResult.from_value(str(number + deps)),
          ...     )

          >>> assert anyio.run(
          ...     RequiresContextFutureResult.from_value(2).bind(function),
          ...     3,
          ... ) == IOSuccess('5')
          >>> assert anyio.run(
          ...     RequiresContextFutureResult.from_failure(2).bind(function),
          ...     3,
          ... ) == IOFailure(2)

        """
        return RequiresContextFutureResult(
            lambda deps: self(deps).bind(
                lambda inner: dekind(  # type: ignore[misc]
                    function(inner),
                )(deps),
            ),
        )
示例#20
0
文件: future.py 项目: ashuein/returns
    def apply(
        self,
        container: Kind2[
            'FutureResult',
            Callable[[_ValueType], _NewValueType],
            _ErrorType,
        ],
    ) -> 'FutureResult[_NewValueType, _ErrorType]':
        """
        Calls a wrapped function in a container on this container.

        .. code:: python

          >>> import anyio
          >>> from returns.future import FutureResult
          >>> from returns.io import IOSuccess, IOFailure

          >>> def appliable(x: int) -> int:
          ...    return x + 1

          >>> assert anyio.run(
          ...     FutureResult.from_value(1).apply(
          ...         FutureResult.from_value(appliable),
          ...     ).awaitable,
          ... ) == IOSuccess(2)
          >>> assert anyio.run(
          ...     FutureResult.from_failure(1).apply(
          ...         FutureResult.from_value(appliable),
          ...     ).awaitable,
          ... ) == IOFailure(1)

          >>> assert anyio.run(
          ...     FutureResult.from_value(1).apply(
          ...         FutureResult.from_failure(2),
          ...     ).awaitable,
          ... ) == IOFailure(2)
          >>> assert anyio.run(
          ...     FutureResult.from_failure(1).apply(
          ...         FutureResult.from_failure(2),
          ...     ).awaitable,
          ... ) == IOFailure(1)

        """
        return FutureResult(_future_result.async_apply(
            dekind(container), self._inner_value,
        ))
    def bind(
        self,
        function: Callable[
            [_ValueType],
            Kind3[
                'RequiresContextIOResult',
                _NewValueType,
                _ErrorType,
                _EnvType,
            ],
        ],
    ) -> 'RequiresContextIOResult[_NewValueType, _ErrorType, _EnvType]':
        """
        Composes this container with a function returning the same type.

        .. code:: python

          >>> from returns.context import RequiresContextIOResult
          >>> from returns.io import IOSuccess, IOFailure

          >>> def first(lg: bool) -> RequiresContextIOResult[int, int, float]:
          ...     # `deps` has `float` type here:
          ...     return RequiresContextIOResult(
          ...         lambda deps: IOSuccess(deps) if lg else IOFailure(-deps),
          ...     )

          >>> def second(
          ...     number: int,
          ... ) -> RequiresContextIOResult[str, int, float]:
          ...     # `deps` has `float` type here:
          ...     return RequiresContextIOResult(
          ...         lambda deps: IOSuccess('>=' if number >= deps else '<'),
          ...     )

          >>> assert first(True).bind(second)(1) == IOSuccess('>=')
          >>> assert first(False).bind(second)(2) == IOFailure(-2)

        """
        return RequiresContextIOResult(
            lambda deps: self(deps).bind(
                lambda inner: dekind(  # type: ignore[misc]
                    function(inner),
                )(deps),
            ),
        )
示例#22
0
    def apply(
        self,
        container: Kind2['RequiresContext',
                         Callable[[_ReturnType], _NewReturnType], _EnvType, ],
    ) -> RequiresContext[_NewReturnType, _EnvType]:
        """
        Calls a wrapped function in a container on this container.

        .. code:: python

          >>> from returns.context import RequiresContext
          >>> assert RequiresContext.from_value('a').apply(
          ...    RequiresContext.from_value(lambda inner: inner + 'b')
          ... )(...) == 'ab'

        """
        return RequiresContext(
            lambda deps: self.map(dekind(container)(deps))(deps), )
示例#23
0
文件: io.py 项目: nurumaik/returns
    def from_iterable(
        cls,
        inner_value: Iterable[Kind1['IO', _ValueType]],
    ) -> 'IO[Sequence[_ValueType]]':
        """
        Transforms an iterable of ``IO`` containers into a single container.

        .. code:: python

          >>> from returns.io import IO

          >>> assert IO.from_iterable([
          ...    IO(1),
          ...    IO(2),
          ... ]) == IO((1, 2))

        """
        return dekind(iterable_kind(cls, inner_value))
示例#24
0
    def bind(
        self,
        function: Callable[[_ValueType], Kind1['IO', _NewValueType]],
    ) -> 'IO[_NewValueType]':
        """
        Applies 'function' to the result of a previous calculation.

        'function' should accept a single "normal" (non-container) argument
        and return ``IO`` type object.

        .. code:: python

          >>> def bindable(string: str) -> IO[str]:
          ...      return IO(string + 'b')

          >>> assert IO('a').bind(bindable) == IO('ab')

        """
        return dekind(function(self._inner_value))
示例#25
0
    def from_iterable(
        cls,
        inner_value: Iterable[Kind2['RequiresContext', _ValueType, _EnvType]],
    ) -> 'RequiresContext[Sequence[_ValueType], _EnvType]':
        """
        Transforms an iterable of ``RequiresContext`` containers.

        Returns a single container with a sequence of values.

        .. code:: python

          >>> from returns.context import RequiresContext

          >>> assert RequiresContext.from_iterable([
          ...    RequiresContext.from_value(1),
          ...    RequiresContext.from_value(2),
          ... ])(...) == (1, 2)

        """
        return dekind(iterable_kind(cls, inner_value))
示例#26
0
    def from_iterable(
        cls,
        inner_value: Iterable[Kind1['Future', _ValueType]],
    ) -> 'Future[Sequence[_ValueType]]':
        """
        Transforms an iterable of ``Future`` containers into a single container.

        .. code:: python

          >>> import anyio
          >>> from returns.future import Future
          >>> from returns.io import IO

          >>> assert anyio.run(Future.from_iterable([
          ...    Future.from_value(1),
          ...    Future.from_value(2),
          ... ]).awaitable) == IO((1, 2))

        """
        return dekind(iterable_kind(cls, inner_value))
示例#27
0
    def apply(
        self,
        container: Kind1['Future', Callable[[_ValueType], _NewValueType]],
    ) -> 'Future[_NewValueType]':
        """
        Calls a wrapped function in a container on this container.

        .. code:: python

          >>> import anyio
          >>> from returns.future import Future

          >>> def transform(arg: int) -> str:
          ...      return str(arg) + 'b'

          >>> assert anyio.run(
          ...     Future.from_value(1).apply(
          ...         Future.from_value(transform),
          ...     ).awaitable,
          ... ) == IO('1b')

        """
        return Future(_future.async_apply(dekind(container), self._inner_value))
示例#28
0
 def map_filter(fa: Kind1["TList", A], f: Func1[A, "Option.Option[B]"]) -> Kind1["TList", B]:
   return TList([f(a).get for a in dekind(fa) if f(a).non_empty()])
示例#29
0
 def flat_map(fa: Kind1["TList", A], f: Func1[A, Kind1["TList", B]]) -> Kind1["TList", B]:
   return TList([b for a in dekind(fa) for b in dekind(f(a))])
示例#30
0
 def fold_left(fa: Kind1[Option, A], b: B, f: Func2[B, A, B]) -> B:
     ff: Func1[A, B] = lambda a: f(b, a)
     return dekind(fa).fold(b, ff)