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:
...| Attribute | Type | Description |
|---|---|---|
A_co | = TypeVar('A_co', covariant=True) |
Classes#
Functions#
from_optional#
from_optional(value) -> Option[A]None stays absent; anything else is present.
| Parameter | Type | Description |
|---|---|---|
value | A | 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.
| Parameter | Type | Description |
|---|---|---|
items | Iterable[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]| Parameter | Type | Description |
|---|---|---|
option | Option[A] | |
f | Callable[[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]| Parameter | Type | Description |
|---|---|---|
option | Option[A] | |
f | Callable[[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| Parameter | Type | Description |
|---|---|---|
option | Option[A] | |
f | Callable[[], 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.valueget_or_none#
get_or_none(option) -> A | NoneBack to A | None, losing the distinction Option keeps.
| Parameter | Type | Description |
|---|---|---|
option | Option[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.valueget_or_raise#
get_or_raise(option) -> AThe value, or raise NoSuchElementException.
| Parameter | Type | Description |
|---|---|---|
option | Option[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