We have several helpers to convert containers from one type to another and back again.
We have two converters to work with Result <-> Maybe
transformations:
maybe_to_result()
that converts Maybe
to Result
result_to_maybe()
that converts Result
to Maybe
That’s how they work:
>>> from returns.converters import maybe_to_result, result_to_maybe
>>> from returns.maybe import Maybe, Some
>>> from returns.result import 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)
Take a note, that type changes.
Also, take a note that Success(None)
will be converted to Nothing
.
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)
Joins two nested containers together.
Please, note that it will not join
two Failure
for Result
case
or two Nothing
for Maybe
case
(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
container (KindN
[TypeVar
(_BindableKind
, bound= BindableN
), KindN
[TypeVar
(_BindableKind
, bound= BindableN
), TypeVar
(_FirstType
), TypeVar
(_SecondType
), TypeVar
(_ThirdType
)], TypeVar
(_SecondType
), TypeVar
(_ThirdType
)]) –
KindN
[TypeVar
(_BindableKind
, bound= BindableN
), TypeVar
(_FirstType
), TypeVar
(_SecondType
), TypeVar
(_ThirdType
)]
Converts Result
container to Maybe
container.
>>> 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
Converts Maybe
container to Result
container.
>>> 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)