Package pyfplib

Sub-modules

pyfplib.either

This module provides Either type and two constructors of Either: Left[L, R] and Right[L, R].

pyfplib.errors

This module provides errors of pyfplib.

pyfplib.functions
pyfplib.iterator
pyfplib.option

This module provides Result[T] type and two constructors of Option: Ok[T] and Err[T].

pyfplib.result

Functions

def all_of(callback: Callable[[Any], bool], iterable: Iterable[Any]) ‑> bool
Expand source code
def all_of(callback: Callable[[Any], bool], iterable: Iterable[Any]) -> bool:
    ret_value = True
    for item in iterable:
        ret_value = callback(item)
        if not ret_value:
            break
    return ret_value
def any_of(callback: Callable[[Any], bool], iterable: Iterable[Any]) ‑> bool
Expand source code
def any_of(callback: Callable[[Any], bool], iterable: Iterable[Any]) -> bool:
    ret_value = False
    for item in iterable:
        ret_value = callback(item)
        if ret_value:
            break
    return ret_value
def fold(callback: Callable[[Any, Any], Any],
iterable: Iterable[Any],
first: Any | None = None) ‑> Any
Expand source code
def fold(
    callback: Callable[[Any, Any], Any],
    iterable: Iterable[Any],
    first: Union[Any, None] = None,
) -> Any:
    ret_value = first
    for item in iterable:
        ret_value = callback(ret_value, item)
    return ret_value
def for_each(callback: Callable[[Any], None], iterable: Iterable[Any])
Expand source code
def for_each(callback: Callable[[Any], None], iterable: Iterable[Any]):
    """Applies the given callback for each elements of the given iterable object

    Args:
        callback: callback to execute with elements
        iterable: provides elements to apply the callback
    """
    for item in iterable:
        callback(item)

Applies the given callback for each elements of the given iterable object

Args

callback
callback to execute with elements
iterable
provides elements to apply the callback
def head(iterable: Iterable[Any]) ‑> Option[typing.Any]
Expand source code
def head(iterable: Iterable[Any]) -> Option[Any]:
    return Some(iterable[0]) if len(iterable) else Nothing()
def is_empty(iterable: Iterable[Any]) ‑> bool
Expand source code
def is_empty(iterable: Iterable[Any]) -> bool:
    return len(iterable) == 0
def is_not_empty(iterable: Iterable[Any]) ‑> bool
Expand source code
def is_not_empty(iterable: Iterable[Any]) -> bool:
    return len(iterable) != 0
def last(iterable: Iterable[Any]) ‑> Option[typing.Any]
Expand source code
def last(iterable: Iterable[Any]) -> Option[Any]:
    return Nothing() if len(iterable) == 0 else Some(iterable[-1])
def none_of(callback: Callable[[Any], bool], iterable: Iterable[Any]) ‑> bool
Expand source code
def none_of(callback: Callable[[Any], bool], iterable: Iterable[Any]) -> bool:
    ret_value = True
    for item in iterable:
        ret_value = not callback(item)
        if not ret_value:
            break
    return ret_value
def tail(sequence: Sequence[str]) ‑> Sequence[str]
Expand source code
def tail(sequence: Sequence[str]) -> Sequence[str]:
    return sequence[1:] if len(sequence) else sequence

Classes

class Either (*, left: ~L | None = None, right: ~R | None = None)
Expand source code
class Either(Generic[L, R]):
    """Either is a basic class."""

    def __init__(self, *, left: Optional[L] = None, right: Optional[R] = None):
        self.__left: Optional[L] = left
        self.__right: Optional[R] = right

    def is_left(self) -> bool:
        """Returns True if left value is not None."""
        return self.__left is not None

    def is_right(self) -> bool:
        """Returns True if right value is not None."""
        return self.__right is not None

    def if_lef(self, fn: Callable[[L], None]) -> "Either[L, R]":
        """\
        Calls fn function and returns itself.
        The fn function will be called if the left value is not None.
        """
        if self.is_left():
            fn(cast(L, self.__left))
        return self

    def if_right(self, fn: Callable[[R], None]) -> "Either[L, R]":
        """\
        Calls fn function and returns itself.
        The fn function will be called if the right value is not None.
        """
        if self.is_right():
            fn(cast(R, self.__right))
        return self

    def left(self) -> Option[L]:
        """Returns left value as Option[L]."""
        return Option.from_optional(self.__left)

    def right(self) -> Option[R]:
        """Returns right value as Option[R]."""
        return Option.from_optional(self.__right)

    def map_left(self, fn: Callable[[L], U]) -> "Either[U, R]":
        """Maps an Either[L, R] to Either[U, R]."""
        either: Either[U, R]
        if self.is_left():
            either = Left[U, R](fn(cast(L, self.__left)))
        else:
            either = Right[U, R](cast(R, self.__right))
        return either

    def map_right(self, fn: Callable[[R], U]) -> "Either[L, U]":
        """Maps an Either[L, R] to Either[L, U]."""
        either: Either[L, U]
        if self.is_right():
            either = Right[L, U](fn(cast(R, self.__right)))
        else:
            either = Left[L, U](cast(L, self.__left))
        return either

    @staticmethod
    def from_result(result: Result) -> "Either[T, Exception]":
        """Creates Either[T, Exception] from Result."""
        either: Either
        if result.is_ok():
            either = Left[T, Exception](cast(T, result.ok().unwrap()))
        else:
            either = Right[T, Exception](cast(Exception, result.err().unwrap()))
        return either

Either is a basic class.

Ancestors

  • typing.Generic

Subclasses

Static methods

def from_result(result: Result) ‑> Either[~T, Exception]
Expand source code
@staticmethod
def from_result(result: Result) -> "Either[T, Exception]":
    """Creates Either[T, Exception] from Result."""
    either: Either
    if result.is_ok():
        either = Left[T, Exception](cast(T, result.ok().unwrap()))
    else:
        either = Right[T, Exception](cast(Exception, result.err().unwrap()))
    return either

Creates Either[T, Exception] from Result.

Methods

def if_lef(self, fn: Callable[[~L], None]) ‑> Either[~L, ~R]
Expand source code
def if_lef(self, fn: Callable[[L], None]) -> "Either[L, R]":
    """\
    Calls fn function and returns itself.
    The fn function will be called if the left value is not None.
    """
    if self.is_left():
        fn(cast(L, self.__left))
    return self

Calls fn function and returns itself. The fn function will be called if the left value is not None.

def if_right(self, fn: Callable[[~R], None]) ‑> Either[~L, ~R]
Expand source code
def if_right(self, fn: Callable[[R], None]) -> "Either[L, R]":
    """\
    Calls fn function and returns itself.
    The fn function will be called if the right value is not None.
    """
    if self.is_right():
        fn(cast(R, self.__right))
    return self

Calls fn function and returns itself. The fn function will be called if the right value is not None.

def is_left(self) ‑> bool
Expand source code
def is_left(self) -> bool:
    """Returns True if left value is not None."""
    return self.__left is not None

Returns True if left value is not None.

def is_right(self) ‑> bool
Expand source code
def is_right(self) -> bool:
    """Returns True if right value is not None."""
    return self.__right is not None

Returns True if right value is not None.

def left(self) ‑> Option[~L]
Expand source code
def left(self) -> Option[L]:
    """Returns left value as Option[L]."""
    return Option.from_optional(self.__left)

Returns left value as Option[L].

def map_left(self, fn: Callable[[~L], ~U]) ‑> Either[~U, ~R]
Expand source code
def map_left(self, fn: Callable[[L], U]) -> "Either[U, R]":
    """Maps an Either[L, R] to Either[U, R]."""
    either: Either[U, R]
    if self.is_left():
        either = Left[U, R](fn(cast(L, self.__left)))
    else:
        either = Right[U, R](cast(R, self.__right))
    return either

Maps an Either[L, R] to Either[U, R].

def map_right(self, fn: Callable[[~R], ~U]) ‑> Either[~L, ~U]
Expand source code
def map_right(self, fn: Callable[[R], U]) -> "Either[L, U]":
    """Maps an Either[L, R] to Either[L, U]."""
    either: Either[L, U]
    if self.is_right():
        either = Right[L, U](fn(cast(R, self.__right)))
    else:
        either = Left[L, U](cast(L, self.__left))
    return either

Maps an Either[L, R] to Either[L, U].

def right(self) ‑> Option[~R]
Expand source code
def right(self) -> Option[R]:
    """Returns right value as Option[R]."""
    return Option.from_optional(self.__right)

Returns right value as Option[R].

class Err (error: ~E)
Expand source code
class Err(Result[T, E]):
    """Result constructor."""

    def __init__(self, error: E):
        super().__init__(error=error)

Result constructor.

Ancestors

Inherited members

class Left (value: ~L)
Expand source code
class Left(Either[L, R]):
    """\
    This Either constructor creates a new instance of Either
    with a left value.
    """

    def __init__(self, value: L):
        super().__init__(left=value)

    @property
    def value(self) -> Union[L, R]:
        """Getter returns left or right value."""
        return cast(L, self.left())

This Either constructor creates a new instance of Either with a left value.

Ancestors

Instance variables

prop value : ~L | ~R
Expand source code
@property
def value(self) -> Union[L, R]:
    """Getter returns left or right value."""
    return cast(L, self.left())

Getter returns left or right value.

Inherited members

class Nothing
Expand source code
class Nothing(Option[T]):
    """
    Nothing extends Option[T].
    It is used to create empty Option[T]

    Usage:
        Nothing() - no value contained.
    """

    def __init__(self):
        super().__init__(None)

Nothing extends Option[T]. It is used to create empty Option[T]

Usage

Nothing() - no value contained.

Internal constructor - use Some(value) or Nothing() instead.

Args

value
The contained value or None for Nothing

Ancestors

Inherited members

class Ok (value: ~T)
Expand source code
class Ok(Result[T, E]):
    """Result constructor."""

    def __init__(self, value: T):
        super().__init__(value=value)

Result constructor.

Ancestors

Inherited members

class Option (value: ~T | None)
Expand source code
class Option(Generic[T]):
    """
    Rust-inspired Option<T> monad for Python.

    Represents a value that is either Some(T) containing data,
    or Nothing() representing absence of value.

    Provides safe null-handling through method chaining
    instead of explicit None checks.
    """

    # Support for structural pattern matching (Python 3.10+)
    __match_args__ = ("value",)

    def __init__(self, value: Optional[T]):
        """
        Internal constructor - use Some(value) or Nothing() instead.

        Args:
            value: The contained value or None for Nothing
        """
        self.__value = value

    @property
    def value(self) -> Optional[T]:
        """Returns the raw contained value (use with caution - may be None)."""
        return self.__value

    def is_some(self) -> bool:
        """Returns True if this Option contains a value (Some[T])."""
        return self.__value is not None

    def is_none(self) -> bool:
        """Returns True if this Option contains no value (Nothing)."""
        return self.__value is None

    def if_some(self, fn: Callable[[T], None]) -> "Option[T]":
        """
        Executes callback if Some[T], otherwise does nothing.
        Returns self for method chaining.

        Args:
            fn: callback to execute with contained value
        """
        if self.__value is not None:
            fn(self.__value)
        return self

    def if_none(self, fn: Callable[[], None]) -> "Option[T]":
        """
        Executes callback if Nothing, otherwise does nothing.
        Returns self for method chaining.

        Args:
            fn: callback to execute when no value present
        """
        if self.__value is None:
            fn()
        return self

    def unwrap(self) -> T:
        """
        Extracts the contained value, raising UnwrapError if Nothing.

        Raises:
            UnwrapError: When attempting to unwrap Nothing
        """
        if self.__value is None:
            msg = "called `Option.unwrap()` on a `Nothing` value"
            raise UnwrapError(msg)
        return self.__value

    def expect(self, message: str) -> T:
        """Returns contained value or raises ExpectedError"""
        if self.__value is None:
            raise ExpectedError(message)
        return self.__value

    def unwrap_or(self, value: T) -> T:
        """Returns contained value or provided default if Nothing."""
        return value if self.__value is None else self.__value

    def map(self, fn: Callable[[T], U]) -> "Option[U]":
        """
        Maps contained value T -> U, returns Nothing() if no value.
        Preserves Option structure for method chaining.

        Args:
            fn: a pure function mapping T to U
        """
        return Some(fn(self.__value)) if self.__value is not None else Nothing()

    def map_from(self, fn: Callable[[T], "Option[U]"]) -> "Option[U]":
        """
        Maps contained value through a function returning Option[U].
        FlatMaps Option[T] -> Option[U], returns Nothing() if no value.

        Args:
            fn: the function returning Option[U]
        """
        return fn(self.__value) if self.__value is not None else Nothing()

    def __eq__(self, other: object) -> bool:
        """Equality comparison based on contained values."""
        ret: bool = False
        if isinstance(other, Option):
            ret = self.__value == other.value
        return ret

    def __hash__(self):
        return hash(self.__value)

    def __bool__(self) -> bool:
        """Boolean conversion - True if Some[T], False if Nothing."""
        return self.is_some()

    @staticmethod
    def from_optional(value: Optional[T] = None) -> "Option[T]":
        """Creates Option[T] from Optional[T]."""
        return Nothing() if value is None else Some(cast(T, value))

Rust-inspired Option monad for Python.

Represents a value that is either Some(T) containing data, or Nothing() representing absence of value.

Provides safe null-handling through method chaining instead of explicit None checks.

Internal constructor - use Some(value) or Nothing() instead.

Args

value
The contained value or None for Nothing

Ancestors

  • typing.Generic

Subclasses

Static methods

def from_optional(value: ~T | None = None) ‑> Option[~T]
Expand source code
@staticmethod
def from_optional(value: Optional[T] = None) -> "Option[T]":
    """Creates Option[T] from Optional[T]."""
    return Nothing() if value is None else Some(cast(T, value))

Creates Option[T] from Optional[T].

Instance variables

prop value : ~T | None
Expand source code
@property
def value(self) -> Optional[T]:
    """Returns the raw contained value (use with caution - may be None)."""
    return self.__value

Returns the raw contained value (use with caution - may be None).

Methods

def expect(self, message: str) ‑> ~T
Expand source code
def expect(self, message: str) -> T:
    """Returns contained value or raises ExpectedError"""
    if self.__value is None:
        raise ExpectedError(message)
    return self.__value

Returns contained value or raises ExpectedError

def if_none(self, fn: Callable[[], None]) ‑> Option[~T]
Expand source code
def if_none(self, fn: Callable[[], None]) -> "Option[T]":
    """
    Executes callback if Nothing, otherwise does nothing.
    Returns self for method chaining.

    Args:
        fn: callback to execute when no value present
    """
    if self.__value is None:
        fn()
    return self

Executes callback if Nothing, otherwise does nothing. Returns self for method chaining.

Args

fn
callback to execute when no value present
def if_some(self, fn: Callable[[~T], None]) ‑> Option[~T]
Expand source code
def if_some(self, fn: Callable[[T], None]) -> "Option[T]":
    """
    Executes callback if Some[T], otherwise does nothing.
    Returns self for method chaining.

    Args:
        fn: callback to execute with contained value
    """
    if self.__value is not None:
        fn(self.__value)
    return self

Executes callback if Some[T], otherwise does nothing. Returns self for method chaining.

Args

fn
callback to execute with contained value
def is_none(self) ‑> bool
Expand source code
def is_none(self) -> bool:
    """Returns True if this Option contains no value (Nothing)."""
    return self.__value is None

Returns True if this Option contains no value (Nothing).

def is_some(self) ‑> bool
Expand source code
def is_some(self) -> bool:
    """Returns True if this Option contains a value (Some[T])."""
    return self.__value is not None

Returns True if this Option contains a value (Some[T]).

def map(self, fn: Callable[[~T], ~U]) ‑> Option[~U]
Expand source code
def map(self, fn: Callable[[T], U]) -> "Option[U]":
    """
    Maps contained value T -> U, returns Nothing() if no value.
    Preserves Option structure for method chaining.

    Args:
        fn: a pure function mapping T to U
    """
    return Some(fn(self.__value)) if self.__value is not None else Nothing()

Maps contained value T -> U, returns Nothing() if no value. Preserves Option structure for method chaining.

Args

fn
a pure function mapping T to U
def map_from(self,
fn: Callable[[~T], ForwardRef('Option[U]')]) ‑> Option[~U]
Expand source code
def map_from(self, fn: Callable[[T], "Option[U]"]) -> "Option[U]":
    """
    Maps contained value through a function returning Option[U].
    FlatMaps Option[T] -> Option[U], returns Nothing() if no value.

    Args:
        fn: the function returning Option[U]
    """
    return fn(self.__value) if self.__value is not None else Nothing()

Maps contained value through a function returning Option[U]. FlatMaps Option[T] -> Option[U], returns Nothing() if no value.

Args

fn
the function returning Option[U]
def unwrap(self) ‑> ~T
Expand source code
def unwrap(self) -> T:
    """
    Extracts the contained value, raising UnwrapError if Nothing.

    Raises:
        UnwrapError: When attempting to unwrap Nothing
    """
    if self.__value is None:
        msg = "called `Option.unwrap()` on a `Nothing` value"
        raise UnwrapError(msg)
    return self.__value

Extracts the contained value, raising UnwrapError if Nothing.

Raises

UnwrapError
When attempting to unwrap Nothing
def unwrap_or(self, value: ~T) ‑> ~T
Expand source code
def unwrap_or(self, value: T) -> T:
    """Returns contained value or provided default if Nothing."""
    return value if self.__value is None else self.__value

Returns contained value or provided default if Nothing.

class Result (*, value: ~T | None = None, error: ~E | None = None)
Expand source code
class Result(Generic[T, E]):
    __match_args__ = ("value",)

    def __init__(self, *, value: Optional[T] = None, error: Optional[E] = None):
        if error is None:
            self.__value = value
            self.__is_ok = True
        else:
            self.__value = error
            self.__is_ok = False

    @property
    def value(self) -> Union[T, E]:
        """Returns a raw value."""
        return self.__value

    def is_ok(self) -> bool:
        """Returns True if the option is Ok[T]."""
        return self.__is_ok

    def is_err(self) -> bool:
        """Returns True if the option is Err[T]."""
        return not self.__is_ok

    def if_ok(self, fn: Callable[[T], None]) -> "Result[T, E]":
        """\
        Calls fn function and returns itself.
        The fn function will be called if this option is Ok[T].
        """
        if self.is_ok():
            fn(self.__value)
        return self

    def if_err(self, fn: Callable[[E], None]) -> "Result[T, E]":
        """\
        Calls fn function and returns itself.
        The fn function will be called if this option is Err[E].
        """
        if self.is_err():
            fn(self.__value)
        return self

    def ok(self) -> Option[T]:
        """\
        Returns Some[T] if this option is Ok[T],
        otherwise it returns Nothing[T].
        """
        return Some(self.__value) if self.is_ok() else Nothing()

    def err(self) -> Option[E]:
        """\
        Returns Some[Exception] if this option is Err[E],
        otherwise it returns Nothing[Exception].
        """
        option: Option[Exception]
        if self.is_err():
            option = Some[Exception](cast(Exception, self.__value))
        else:
            option = Nothing[Exception]()
        return option

    def unwrap(self) -> T:
        """
        Extracts the contained value, raising UnwrapError if Err.

        Raises:
            UnwrapError: When attempting to unwrap Err
        """
        if self.is_err():
            msg = "called `Result.unwrap()` on a `Err` value"
            raise UnwrapError(msg)
        return self.__value

    def unwrap_err(self) -> E:
        """
        Extracts the contained error, raising UnwrapError if Ok.

        Raises:
            UnwrapError: When attempting to unwrap Ok
        """
        if self.is_ok():
            msg = "called `Result.unwrap_err()` on a `Ok` value"
            raise UnwrapError(msg)
        return self.__value

    def expect(self, message: str) -> T:
        """Returns contained value or raises ExpectedError"""
        if self.is_err():
            raise ExpectedError(message)
        return self.__value

    def expect_err(self, message: str) -> E:
        """Returns contained value or raises ExpectedError"""
        if self.is_ok():
            raise ExpectedError(message)
        return self.__value

    def unwrap_or(self, value: T) -> T:
        """Returns contained value or provided default if Err."""
        return self.__value if self.is_ok() is None else value

    def unwrap_err_or(self, value: E) -> E:
        """Returns contained value or provided default if Ok."""
        return self.__value if self.is_err() is None else value

    def map(self, fn: Callable[[T], U]) -> "Result[U, E]":
        """Maps an Result[T, E] to Result[U, E]"""
        result: Result[U, E]
        if self.is_ok():
            result = Ok[U, E](fn(cast(T, self.__value)))
        else:
            result = Err[U, E](cast(E, self.__value))
        return result

    def map_or(self, default: T, fn: Callable[[T], U]) -> "Result[U]":
        """Maps an Result[T] to Result[U]"""
        result: Result[U]
        if self.is_ok():
            result = fn(self.__value)
        else:
            result = fn(default)
        return result

    @staticmethod
    def try_call(fn: Callable[..., R], *args, **kwargs) -> "Result[R, E]":
        """Tries to call fn function and returns a result of the execution."""
        try:
            ret: R = fn(*args, **kwargs)
            return Ok[R, E](ret)
        except Exception as err:
            return Err[R, E](err)

Abstract base class for generic types.

On Python 3.12 and newer, generic classes implicitly inherit from Generic when they declare a parameter list after the class's name::

class Mapping[KT, VT]:
    def __getitem__(self, key: KT) -> VT:
        ...
    # Etc.

On older versions of Python, however, generic classes have to explicitly inherit from Generic.

After a class has been declared to be generic, it can then be used as follows::

def lookup_name[KT, VT](mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
    try:
        return mapping[key]
    except KeyError:
        return default

Ancestors

  • typing.Generic

Subclasses

Static methods

def try_call(fn: Callable[..., ~R], *args, **kwargs) ‑> Result[~R, ~E]
Expand source code
@staticmethod
def try_call(fn: Callable[..., R], *args, **kwargs) -> "Result[R, E]":
    """Tries to call fn function and returns a result of the execution."""
    try:
        ret: R = fn(*args, **kwargs)
        return Ok[R, E](ret)
    except Exception as err:
        return Err[R, E](err)

Tries to call fn function and returns a result of the execution.

Instance variables

prop value : ~T | ~E
Expand source code
@property
def value(self) -> Union[T, E]:
    """Returns a raw value."""
    return self.__value

Returns a raw value.

Methods

def err(self) ‑> Option[~E]
Expand source code
def err(self) -> Option[E]:
    """\
    Returns Some[Exception] if this option is Err[E],
    otherwise it returns Nothing[Exception].
    """
    option: Option[Exception]
    if self.is_err():
        option = Some[Exception](cast(Exception, self.__value))
    else:
        option = Nothing[Exception]()
    return option

Returns Some[Exception] if this option is Err[E], otherwise it returns Nothing[Exception].

def expect(self, message: str) ‑> ~T
Expand source code
def expect(self, message: str) -> T:
    """Returns contained value or raises ExpectedError"""
    if self.is_err():
        raise ExpectedError(message)
    return self.__value

Returns contained value or raises ExpectedError

def expect_err(self, message: str) ‑> ~E
Expand source code
def expect_err(self, message: str) -> E:
    """Returns contained value or raises ExpectedError"""
    if self.is_ok():
        raise ExpectedError(message)
    return self.__value

Returns contained value or raises ExpectedError

def if_err(self, fn: Callable[[~E], None]) ‑> Result[~T, ~E]
Expand source code
def if_err(self, fn: Callable[[E], None]) -> "Result[T, E]":
    """\
    Calls fn function and returns itself.
    The fn function will be called if this option is Err[E].
    """
    if self.is_err():
        fn(self.__value)
    return self

Calls fn function and returns itself. The fn function will be called if this option is Err[E].

def if_ok(self, fn: Callable[[~T], None]) ‑> Result[~T, ~E]
Expand source code
def if_ok(self, fn: Callable[[T], None]) -> "Result[T, E]":
    """\
    Calls fn function and returns itself.
    The fn function will be called if this option is Ok[T].
    """
    if self.is_ok():
        fn(self.__value)
    return self

Calls fn function and returns itself. The fn function will be called if this option is Ok[T].

def is_err(self) ‑> bool
Expand source code
def is_err(self) -> bool:
    """Returns True if the option is Err[T]."""
    return not self.__is_ok

Returns True if the option is Err[T].

def is_ok(self) ‑> bool
Expand source code
def is_ok(self) -> bool:
    """Returns True if the option is Ok[T]."""
    return self.__is_ok

Returns True if the option is Ok[T].

def map(self, fn: Callable[[~T], ~U]) ‑> Result[~U, ~E]
Expand source code
def map(self, fn: Callable[[T], U]) -> "Result[U, E]":
    """Maps an Result[T, E] to Result[U, E]"""
    result: Result[U, E]
    if self.is_ok():
        result = Ok[U, E](fn(cast(T, self.__value)))
    else:
        result = Err[U, E](cast(E, self.__value))
    return result

Maps an Result[T, E] to Result[U, E]

def map_or(self, default: ~T, fn: Callable[[~T], ~U]) ‑> Result[U]
Expand source code
def map_or(self, default: T, fn: Callable[[T], U]) -> "Result[U]":
    """Maps an Result[T] to Result[U]"""
    result: Result[U]
    if self.is_ok():
        result = fn(self.__value)
    else:
        result = fn(default)
    return result

Maps an Result[T] to Result[U]

def ok(self) ‑> Option[~T]
Expand source code
def ok(self) -> Option[T]:
    """\
    Returns Some[T] if this option is Ok[T],
    otherwise it returns Nothing[T].
    """
    return Some(self.__value) if self.is_ok() else Nothing()

Returns Some[T] if this option is Ok[T], otherwise it returns Nothing[T].

def unwrap(self) ‑> ~T
Expand source code
def unwrap(self) -> T:
    """
    Extracts the contained value, raising UnwrapError if Err.

    Raises:
        UnwrapError: When attempting to unwrap Err
    """
    if self.is_err():
        msg = "called `Result.unwrap()` on a `Err` value"
        raise UnwrapError(msg)
    return self.__value

Extracts the contained value, raising UnwrapError if Err.

Raises

UnwrapError
When attempting to unwrap Err
def unwrap_err(self) ‑> ~E
Expand source code
def unwrap_err(self) -> E:
    """
    Extracts the contained error, raising UnwrapError if Ok.

    Raises:
        UnwrapError: When attempting to unwrap Ok
    """
    if self.is_ok():
        msg = "called `Result.unwrap_err()` on a `Ok` value"
        raise UnwrapError(msg)
    return self.__value

Extracts the contained error, raising UnwrapError if Ok.

Raises

UnwrapError
When attempting to unwrap Ok
def unwrap_err_or(self, value: ~E) ‑> ~E
Expand source code
def unwrap_err_or(self, value: E) -> E:
    """Returns contained value or provided default if Ok."""
    return self.__value if self.is_err() is None else value

Returns contained value or provided default if Ok.

def unwrap_or(self, value: ~T) ‑> ~T
Expand source code
def unwrap_or(self, value: T) -> T:
    """Returns contained value or provided default if Err."""
    return self.__value if self.is_ok() is None else value

Returns contained value or provided default if Err.

class Right (value: ~R)
Expand source code
class Right(Either[L, R]):
    """\
    This Either constructor creates a new instance of Either
    with a right value.
    """

    def __init__(self, value: R):
        super().__init__(right=value)

    @property
    def value(self) -> Union[L, R]:
        """Getter returns left or right value."""
        return cast(R, self.right())

This Either constructor creates a new instance of Either with a right value.

Ancestors

Instance variables

prop value : ~L | ~R
Expand source code
@property
def value(self) -> Union[L, R]:
    """Getter returns left or right value."""
    return cast(R, self.right())

Getter returns left or right value.

Inherited members

class Some (value: ~T)
Expand source code
class Some(Option[T]):
    """
    Some extends Option[T].
    It is used to create Option[T] containing a value

    Usage:
        Some(123)
        Some("hello")
    """

    def __init__(self, value: T):
        super().__init__(value)

Some extends Option[T]. It is used to create Option[T] containing a value

Usage

Some(123) Some("hello")

Internal constructor - use Some(value) or Nothing() instead.

Args

value
The contained value or None for Nothing

Ancestors

Inherited members