Converters¶
We have several helpers to convert containers from one type to another and back again.
Maybe and Result¶
We have two converters to work with Result <-> Maybe transformations:
maybe_to_result()that convertsMaybetoResultresult_to_maybe()that convertsResulttoMaybe
That’s how they work:
>>> from returns.converters import maybe_to_result, result_to_maybe
>>> from returns.maybe import Maybe, Some, Nothing
>>> from returns.result import Failure, Result, Success
>>> result: Result[int, Exception] = Success(1)
>>> maybe: Maybe[int] = result_to_maybe(result)
>>> assert maybe == Some(1)
>>> new_result: Result[int, None] = maybe_to_result(maybe)
>>> assert new_result == Success(1)
>>> failure_with_default: Result[int, str] = maybe_to_result(Nothing, 'abc')
>>> assert failure_with_default == Failure('abc')
Take a note, that type changes.
Also, take a note that Success(None) will be converted to Nothing.
flatten¶
You can also use
flatten
to merge nested containers together:
>>> from returns.converters import flatten
>>> from returns.maybe import Some
>>> from returns.result import Success
>>> from returns.io import IO
>>> assert flatten(IO(IO(1))) == IO(1)
>>> assert flatten(Some(Some(1))) == Some(1)
>>> assert flatten(Success(Success(1))) == Success(1)
API Reference¶
- flatten(container)[source]¶
Joins two nested containers together.
Please, note that it will not join two
FailureforResultcase or twoNothingforMaybecase (or basically any two error types) together.>>> from returns.converters import flatten >>> from returns.io import IO >>> from returns.result import Failure, Success >>> assert flatten(IO(IO(1))) == IO(1) >>> assert flatten(Success(Success(1))) == Success(1) >>> assert flatten(Failure(Failure(1))) == Failure(Failure(1))
See also
- Parameters:
container (
KindN[TypeVar(_BindableKind, bound=BindableN),KindN[TypeVar(_BindableKind, bound=BindableN),TypeVar(_FirstType),TypeVar(_SecondType),TypeVar(_ThirdType)],TypeVar(_SecondType),TypeVar(_ThirdType)])- Return type:
KindN[TypeVar(_BindableKind, bound=BindableN),TypeVar(_FirstType),TypeVar(_SecondType),TypeVar(_ThirdType)]
- result_to_maybe(result_container)[source]¶
Converts
Resultcontainer toMaybecontainer.>>> from returns.maybe import Some, Nothing >>> from returns.result import Failure, Success >>> assert result_to_maybe(Success(1)) == Some(1) >>> assert result_to_maybe(Success(None)) == Some(None) >>> assert result_to_maybe(Failure(1)) == Nothing >>> assert result_to_maybe(Failure(None)) == Nothing
- maybe_to_result(maybe_container, default_error=None)[source]¶
Converts
Maybecontainer toResultcontainer.With optional
default_errorto be used forFailure’s error value.>>> from returns.maybe import Some, Nothing >>> from returns.result import Failure, Success >>> assert maybe_to_result(Some(1)) == Success(1) >>> assert maybe_to_result(Some(None)) == Success(None) >>> assert maybe_to_result(Nothing) == Failure(None) >>> assert maybe_to_result(Nothing, 'error') == Failure('error')