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:

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.

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 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))
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 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
Parameters:

result_container (Result[TypeVar(_FirstType), TypeVar(_SecondType)]) –

Return type:

Maybe[TypeVar(_FirstType)]

maybe_to_result(maybe_container)[source]

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)
Parameters:

maybe_container (Maybe[TypeVar(_FirstType)]) –

Return type:

Result[TypeVar(_FirstType), None]