Skip to content

Either Implementation

monad_std.either.Left

Bases: Generic[L, R], Either[L, R]

Source code in monad_std/either.py
class Left(t.Generic[L, R], Either[L, R]):
    __value: L

    def __init__(self, value: L):
        self.__value = value

    def __eq__(self, other: object) -> bool:
        if isinstance(other, Left):
            return self.__value == other.__value
        elif isinstance(other, Right):
            return False
        else:
            raise TypeError("An `Either` can only be conpared with another `Either`")

    def __hash__(self: "Left[HL, HR]") -> int:
        return hash((True, self.__value))

    def __str__(self) -> str:
        return str(self.__value)

    def __repr__(self) -> str:
        return f"Either::Left({self.__value})"

    def __instancecheck__(self, instance) -> bool:
        return isinstance(instance, Left)

    def is_left(self) -> bool:
        return True

    def is_right(self) -> bool:
        return False

    def unwrap_left(self) -> L:
        return self.__value

    def unwrap_right(self) -> R:
        raise UnwrapException(
            "Either",
            "Call `Either.unwrap_right` on a `Left` value."
        )

    def unwrap_left_unchecked(self) -> L:
        return self.__value

    def unwrap_right_unchecked(self) -> R:
        # This is safe because the api asks the caller
        # to guarentee the call's safety.
        return None # type: ignore[return-value]

monad_std.either.Right

Bases: Generic[L, R], Either[L, R]

Source code in monad_std/either.py
class Right(t.Generic[L, R], Either[L, R]):
    __value: R

    def __init__(self, value: R):
        self.__value = value

    def __eq__(self, other: object) -> bool:
        if isinstance(other, Right):
            return self.__value == other.__value
        elif isinstance(other, Left):
            return False
        else:
            raise TypeError("An `Either` can only be conpared with another `Either`")

    def __hash__(self: "Right[HL, HR]") -> int:
        return hash((False, self.__value))

    def __str__(self) -> str:
        return str(self.__value)

    def __repr__(self) -> str:
        return f"Either::Right({self.__value})"

    def __instancecheck__(self, instance) -> bool:
        return isinstance(instance, Right)

    def is_left(self) -> bool:
        return False

    def is_right(self) -> bool:
        return True

    def unwrap_left(self) -> L:
        raise UnwrapException(
            "Either",
            "Call `Either.unwrap_left` on a `Right` value."
        )

    def unwrap_right(self) -> R:
        return self.__value

    def unwrap_left_unchecked(self) -> L:
        # This is safe because the api asks the caller
        # to guarentee the call's safety.
        return None # type: ignore[return-value]

    def unwrap_right_unchecked(self) -> R:
        return self.__value