towhee.functional.option.Option

class towhee.functional.option.Option[source]

Bases: Generic[A]

Functional-style error handling.

Option[A] = Some(A) or Empty[A] 1. Some(A): just a container for result; 2. Empty[A]: result is empty, because of input error or computation error;

Examples

>>> a = Some(10)
>>> a.map(lambda x: x/2.0)
Some(5.0)
>>> a.map(lambda x: x/0)
Empty()
>>> b = Empty()
>>> b.map(lambda x: x/2.0)
Empty()

Methods

empty

Return an empty value.

flat_map

Apply boxed version of callable.

get_or_else

Return unboxed value, or default if the value is empty.

is_empty

Return True if the value is empty.

is_some

Return True if the value is boxed value.

map

Apply a function to a value.

of

Return a boxed value.

static empty()[source]

Return an empty value.

Returns:

The empty value.

Return type:

Empty

flat_map(f: Callable[[A], Option[B]]) Option[B][source]

Apply boxed version of callable.

Parameters:

f (Callable[[A], Option[B]]) – Boxed version of callable

Returns:

The boxed value.

Return type:

Option[B]

Examples

>>> Option.of(1).flat_map(lambda x: x+1)
2
>>> Option.empty().flat_map(lambda x: x+1)
Empty()
get_or_else(default)[source]

Return unboxed value, or default if the value is empty.

Parameters:

default (any) – The default value to return.

Returns:

The unboxed value, or default if empty.

Return type:

any

Examples

>>> Option.of(0).get_or_else(1)
0
>>> Option.empty().get_or_else(1)
1
is_empty()[source]

Return True if the value is empty.

Returns:

True if empty.

Return type:

bool

is_some()[source]

Return True if the value is boxed value.

Returns:

True if boxed.

Return type:

bool

map(f: Callable[[A], B]) Option[B][source]

Apply a function to a value.

Parameters:

f (Callable[[A], B]) – A unboxed callable.

Returns:

The boxed return value.

Return type:

Option[B]

static of(x: T)[source]

Return a boxed value.

Parameters:

x (T) – The input value.

Returns:

The boxed value.

Return type:

Some(T)