Skip to content

monad_std.either.Either

Bases: Generic[L, R]

An ancestor class of any Either type, inherited by Left and Right.

convert_either(value, flag) staticmethod

Convert a value to an Either value.

If the flag is True, then the value will be Left. Otherwise, Right.

Examples:

assert Left(5) == Either.convert_either(5, True)
assert Right(5) == Either.convert_either(5, False)

convert_either_by(op) staticmethod

Use a function to create a predicate that can convert value to Either.

If the op returns True, then the value will be converted to Left. Otherwise, Right.

Examples:

1
2
3
cvt = Either.convert_either_by(lambda x: x % 2 == 0)
assert Left(4) == cvt(4)
assert Right(5) == cvt(5)

is_left() abstractmethod

Returns True if the value is a Left.

Examples:

assert Left(5).is_left()
assert not Right(5).is_left()

is_right() abstractmethod

Returns True if the value is a Right.

Examples:

assert not Left(5).is_right()
assert Right(5).is_right()

of_left(value) staticmethod

Create a Left value.

of_right(value) staticmethod

Create a Right value.

unwrap_left() abstractmethod

Returns the contained Left value.

This method may raise an exception.

Raises:

Type Description
UnwrapException

Raises if the value is a Right.

Examples:

1
2
3
4
5
assert Left(5).unwrap_left() == 5
try:
    Right(5).unwrap_left()
except UnwrapException as e:
    assert str(e) == "EitherError: Call `Either.unwrap_left` on a `Right` value."

unwrap_left_unchecked() abstractmethod

Returns the contained Left value.

This method acually returns Optional[L] instead of L. But it hide the None in the type hint.

The null safety should be guaranteed by the caller.

unwrap_right() abstractmethod

Returns the contained Right value.

This method may raise an exception.

Raises:

Type Description
UnwrapException

Raises if the value is a Left.

Examples:

1
2
3
4
5
assert Right(5).unwrap_right() == 5
try:
    Left(5).unwrap_right()
except UnwrapException as e:
    assert str(e) == "EitherError: Call `Either.unwrap_right` on a `Left` value."

unwrap_right_unchecked() abstractmethod

Returns the contained Right value.

This method acually returns Optional[R] instead of R. But it hide the None in the type hint.

The null safety should be guaranteed by the caller.