GitHub

API reference for option.

Some[A] | None: an optional value that stays unambiguous when A itself admits None.

pyfect uses plain X | None wherever X can't be None. Option is for the places where it can: Some(None) is a present None, and None is absence. Take one apart with pattern matching::

match found:
    case Some(value):
        ...
    case None:
        ...
AttributeTypeDescription
A_co= TypeVar('A_co', covariant=True)

Classes

Functions

from_optional

from_optional(value) -> Option[A]

None stays absent; anything else is present.

ParameterTypeDescription
valueA | None

Returns Option[A]

def from_optional[A](value: A | None) -> Option[A]:
    """``None`` stays absent; anything else is present."""
    return None if value is None else Some(value)

from_iterable

from_iterable(items) -> Option[A]

The first item, if there is one.

ParameterTypeDescription
itemsIterable[A]

Returns Option[A]

def from_iterable[A](items: Iterable[A]) -> Option[A]:
    """The first item, if there is one."""
    return next((Some(x) for x in items), None)

map

map(option, f) -> Option[B]
ParameterTypeDescription
optionOption[A]
fCallable[[A], B]

Returns Option[B]

def map[A, B](option: Option[A], f: Callable[[A], B]) -> Option[B]:
    return None if option is None else Some(f(option.value))

flat_map

flat_map(option, f) -> Option[B]
ParameterTypeDescription
optionOption[A]
fCallable[[A], Option[B]]

Returns Option[B]

def flat_map[A, B = Never](option: Option[A], f: Callable[[A], Option[B]]) -> Option[B]:
    return None if option is None else f(option.value)

get_or_else

get_or_else(option, f) -> A | B
ParameterTypeDescription
optionOption[A]
fCallable[[], B]

Returns A | B

def get_or_else[A, B](option: Option[A], f: Callable[[], B]) -> A | B:
    return f() if option is None else option.value

get_or_none

get_or_none(option) -> A | None

Back to A | None, losing the distinction Option keeps.

ParameterTypeDescription
optionOption[A]

Returns A | None

def get_or_none[A](option: Option[A]) -> A | None:
    """Back to ``A | None``, losing the distinction ``Option`` keeps."""
    return None if option is None else option.value

get_or_raise

get_or_raise(option) -> A

The value, or raise NoSuchElementException.

ParameterTypeDescription
optionOption[A]

Returns A

def get_or_raise[A](option: Option[A]) -> A:
    """The value, or raise ``NoSuchElementException``."""
    if option is None:
        raise NoSuchElementException("get_or_raise called on None")
    return option.value