Skip to content

monad_std.option.Option

Bases: Generic[KT]

Option monad for python.

__add__(other)

Alias self.__value.__add__.

Returns:

Type Description
Option[Any]

If both value are Some, this will return Some(self + other). Otherwise, return None.

__and__(other)

Alias bool_and.

__bool__() abstractmethod

Returns False only if contained value is None.

__hash__() abstractmethod

hash(Option) has the same result as its contained value.

__mul__(other)

Alias self.__value.__mul__.

Returns:

Type Description
Option[Any]

If both value are Ok, this will return Ok(self * other). Otherwise, return the first Err.

__or__(other)

Alias bool_or.

__xor__(other)

Alias bool_xor.

and_then(func) abstractmethod

Returns None if the option is None, otherwise calls func with the wrapped value and returns the result. Alias flatmap.

Parameters:

Name Type Description Default
func Callable[[KT], Option[U]]

A callable object to produce the next value.

required

Examples:

1
2
3
assert Option.some(2).and_then(lambda x: Option.some(str(x))) == Option.some('2')
assert Option.some(10).and_then(lambda _: Option.none()) == Option.none()
assert Option.none().and_then(lambda x: Option.some(str(x))) == Option.none()
Often used to chain fallible operations that may return None.
1
2
3
4
5
6
7
8
9
def get_from(l, i):
    try:
        return Option.some(l[i])
    except IndexError:
        return Option.none()

arr_2d = [["A0", "A1"], ["B0", "B1"]]
assert get_from(arr_2d, 0).and_then(lambda row: get_from(row, 1)) == Option.some('A1')
assert get_from(arr_2d, 2).and_then(lambda row: get_from(row, 0)) == Option.none()

bool_and(optb) abstractmethod

Returns None if the option is None, otherwise returns optb. Alias &(__and__).

and is a keyword in Python, so here we use bool_and instead.

Arguments passed to and are eagerly evaluated.
If you are passing the result of a function call, it is recommended to use and_then, which is lazily evaluated.

Parameters:

Name Type Description Default
optb Option[U]

Another option object to do the bool evaluation.

required

Examples:

1
2
3
4
assert Option.some(2).bool_and(Option.none()) == Option.none()
assert Option.none().bool_and(Option.some('foo')) == Option.none()
assert Option.some(2).bool_and(Option.some('bar')) == Option.some('bar')
assert Option.none().bool_and(Option.none()) == Option.none()

bool_or(optb) abstractmethod

Returns the option if it contains a value, otherwise returns optb. Alias ||(__or__).

or is a keyword in Python, so here we use bool_or instead.

Arguments passed to or are eagerly evaluated.
If you are passing the result of a function call, it is recommended to use or_else, which is lazily evaluated.

Parameters:

Name Type Description Default
optb Option[KT]

Another option object to do the bool evaluation.

required

Examples:

1
2
3
4
assert Option.some(2).bool_or(Option.none()) == Option.some(2)
assert Option.none().bool_or(Option.some(100)) == Option.some(100)
assert Option.some(2).bool_or(Option.some(100)) == Option.some(2)
assert Option.none().bool_or(Option.none()) == Option.none()

bool_xor(optb) abstractmethod

Returns Some if exactly one of self, optb is Some, otherwise returns None. Alias ^(__xor__).

Parameters:

Name Type Description Default
optb Option[KT]

Another option object to do the bool evaluation.

required

Examples:

1
2
3
4
assert Option.some(2).bool_xor(Option.none()) == Option.some(2)
assert Option.none().bool_xor(Option.some(2)) == Option.some(2)
assert Option.some(2).bool_xor(Option.some(2)) == Option.none()
assert Option.none().bool_xor(Option.none()) == Option.none()

clone()

Clone self.

clone_from(value) staticmethod

Clone an Option.

expect(msg) abstractmethod

Returns the contained Some value.

Returns the contained Some value, and raise an exception if the value is a None with a custom panic message provided by msg.

Recommended Message Style

We recommend that expect messages are used to describe the reason you expect the Option should be Some.

item = slice.get(0).expect("slice should not be empty");

Hint: If you’re having trouble remembering how to phrase expect error messages, remember to focus on the word “should” as in “env variable should be set by blah” or “the given binary should be available and executable by the current user”.

Parameters:

Name Type Description Default
msg str

The message to display if this option is none.

required

Returns:

Type Description
KT

The contained Some value.

Raises:

Type Description
UnwrapException

Raise an exception if the value is a None with a custom message provided by msg.

Examples:

1
2
3
4
5
6
7
x: Option[str] = Option.some('value')
assert x.expect('hey, this is an `Option::None` object') == 'value'
x: Option[str] = Option.none()
try:
    x.expect('hey, this is an `Option::None` object')
except UnwrapException as e:
    assert str(e) == 'hey, this is an `Option::None` object'

filter(func) abstractmethod

Filter the option.

Returns None if the option is None, otherwise calls predicate with the wrapped value and returns:

  • Some(t) if predicate returns True (where t is the wrapped value), and
  • None if predicate returns False.

This function works similar to builtin.filter(). You can imagine the Option<KT> being an iterator over one or zero elements. filter() lets you decide which elements to keep.

Parameters:

Name Type Description Default
func Callable[[KT], bool]

The callable object decides whether the element should be kept.

required

Examples:

1
2
3
assert Option.none().filter(lambda n: n % 2 == 0) == Option.none()
assert Option.some(3).filter(lambda n: n % 2 == 0) == Option.none()
assert Option.some(4).filter(lambda n: n % 2 == 0) == Option.some(4)

flatmap(func) abstractmethod

Alias of and_then.

flatten()

Converts from Option<Option<KT>> to Option<KT>.

Examples:

1
2
3
assert Option.some(Option.some(6)).flatten() == Option.some(6)
assert Option.some(Option.none()).flatten() == Option.none()
assert Option.none().flatten() == Option.none()
Flattening only removes one level of nesting at a time:
1
2
3
4
assert (Option.some(Option.some(Option.some(6))).flatten()
    == Option.some(Option.some(6)))
assert (Option.some(Option.some(Option.some(6))).flatten().flatten()
    == Option.some(6))

from_nullable(value) staticmethod

Construct an Option from a nullable value.

inspect(func) abstractmethod

Calls the provided closure with the contained value (if Some), and return the option itself.

Parameters:

Name Type Description Default
func Callable[[KT], None]

A callable object which accepts the wrapped value and returns nothing.

required

Examples:

1
2
3
4
5
x = []
Option.some(2).inspect(lambda s: x.append(s))
assert x == [2]
Option.none().inspect(lambda s: x.append(s))
assert x == [2]

is_none() abstractmethod

Returns True if the option is a None value.

Returns:

Type Description
bool

Whether the option is a None value.

Examples:

1
2
3
4
x: Option[int] = Option.some(2)
assert not x.is_none()
x: Option[int] = Option.none()
assert x.is_none()

is_some() abstractmethod

Returns True if the option is a Some value.

Returns:

Type Description
bool

Whether the option is a Some value.

Examples:

1
2
3
4
x: Option[int] = Option.some(2)
assert x.is_some()
x: Option[int] = Option.none()
assert not x.is_some()

is_some_and(func) abstractmethod

Returns true if the option is a Some and the value inside it matches a predicate.

Parameters:

Name Type Description Default
func Callable[[KT], bool]

A callable object which accepts the not-none value of the option and returns a boolean.

required

Returns:

Type Description
bool

Whether the option is a Some and the value inside it matches a predicate.

Examples:

1
2
3
4
5
6
x: Option[int] = Option.some(2)
assert x.is_some_and(lambda v: v > 1)
x: Option[int] = Option.some(0)
assert not x.is_some_and(lambda v: v > 1)
x: Option[int] = Option.none()
assert not x.is_some_and(lambda v: v > 1)

map(func) abstractmethod

Maps an Option<KT> to Option<U> by applying a function to a contained value (if Some) or returns None (if None).

Parameters:

Name Type Description Default
func Callable[[KT], U]

A callable object that accepts the wrapped value and returns the processed value.

required

Returns:

Type Description
Option[U]

Returns Option::Some(U) if the option is Some and returns None otherwise.

Examples:

1
2
3
4
5
maybe_some_string = Option.some("Hello, World!")
# `Option::map` will create a new option object
maybe_some_len = maybe_some_string.map(lambda s: len(s))
assert maybe_some_len == Option.some(13)
assert Option.none().map(lambda s: len(s)) == Option.none()

map_mut(func) abstractmethod

Maps and Option<KT> by changing its wrapped value.

This method require a function to return nothing, and passes a reference into it. Actually, python doesn't differentiate mutable / immutable value, and this method is just for explicit notification.

Parameters:

Name Type Description Default
func Callable[[KT], None]

A callable object that accepts the wrapped value.

required

Examples:

class Test:
    value: int
    def __init__(self, val: int):
        self.value = val

    def change_value(self, new_value: int):
        print('old:', self.value, 'new:', new_value)
        self.value = new_value

maybe_something = Option.some(Test(1))
assert maybe_something.unwrap().value == 1
maybe_something.map_mut(lambda x: x.change_value(5))
assert maybe_something.unwrap().value == 5

map_or(default, func) abstractmethod

Returns the provided default result (if none), or applies a function to the contained value (if any).

Arguments passed to map_or are eagerly evaluated.
If you are passing the result of a function call, it is recommended to use map_or_else, which is lazily evaluated.

Parameters:

Name Type Description Default
default U

The default value if the option is None.

required
func Callable[[KT], U]

The function to apply to the contained value.

required

Examples:

assert Option.some('foo').map_or(42, lambda s: len(s)) == 3
assert Option.none().map_or(42, lambda s: len(s)) == 42

map_or_else(default, func) abstractmethod

Computes a default function result (if none), or applies a different function to the contained value (if any).

Parameters:

Name Type Description Default
default Callable[[], U]

The function to produce a default value.

required
func Callable[[KT], U]

The function to apply to the contained value.

required

Examples:

1
2
3
k = 21
assert Option.some('bar').map_or_else(lambda: 2 * k, lambda s: len(s)) == 3
assert Option.none().map_or_else(lambda: 2 * k, lambda s: len(s)) == 42

none() staticmethod

Create a value of None.

Returns:

Type Description
Option[KT]

Option::None

ok_or(err) abstractmethod

Transforms the Option<KT> into a Result<KT, E>, mapping Some(v) to Ok(v) and None to Err(err).

Arguments passed to ok_or are eagerly evaluated.
If you are passing the result of a function call, it is recommended to use ok_or_else, which is lazily evaluated.

Parameters:

Name Type Description Default
err E

A value representing an error

required

Examples:

assert Option.some('foo').ok_or(0) == Result.of_ok('foo')
assert Option.none().ok_or(0) == Result.of_err(0)

ok_or_else(err) abstractmethod

Transforms the Option<KT> into a Result<KT, E>, mapping Some(v) to Ok(v) and None to Err(err()).

Parameters:

Name Type Description Default
err Callable[[], E]

A callable object that returns an error value.

required

Examples:

1
2
3
k = 21
assert Option.some('foo').ok_or_else(lambda: k * 2) == Result.of_ok('foo')
assert Option.none().ok_or_else(lambda: k * 2) == Result.of_err(42)

or_else(func) abstractmethod

Returns the option if it contains a value, otherwise calls func and returns the result.

Parameters:

Name Type Description Default
func Callable[[], Option[KT]]

A callable object to produce the next value.

required

Examples:

1
2
3
assert Option.some('foo').or_else(lambda: Option.some('bar')) == Option.some('foo')
assert Option.none().or_else(lambda: Option.some('bar')) == Option.some('bar')
assert Option.none().or_else(lambda: Option.none()) == Option.none()

some(value) staticmethod

Create a value of Some(KT).

Parameters:

Name Type Description Default
value KT

Some value of type KT.

required

Returns:

Type Description
Option[KT]

Option::Some(KT)

to_array() abstractmethod

Returns an array of the possible contained value.

Examples:

assert Option.some(1).to_array() == [1]
assert Option.none().to_array() == []

to_iter()

Alias iter(self.to_array()).

to_nullable() abstractmethod

Returns the contained value. If self is an Option::None, this will return Python's None directly.

Note: If the wrapped object is None itself, this will also return None as it's wrapped by the Some. It's impossible to distinguish between Option::Some(None) and Option::None by using this method.

Returns:

Type Description
Optional[KT]

The contained value.

Examples:

1
2
3
4
5
6
x: Option[str] = Option.some("air")
assert x.to_nullable() == "air"
x: Option[str] = Option.none()
assert x.to_nullable() is None
x: Option[None] = Option.some(None)
assert x.to_nullable() is None

to_pattern() abstractmethod

Returns the contained value for pattern-matching.

This is the same as Option.to_nullable().

transpose()

Transposes an Option of a Result into a Result of an Option.

None will be mapped to Ok(None). Some(Ok(_)) and Some(Err(_)) will be mapped to Ok(Some(_)) and Err(_).

Examples:

1
2
3
x = Result.of_ok(Option.some(5))
y = Option.some(Result.of_ok(5))
assert x == y.transpose()

unwrap() abstractmethod

Returns the contained Some value.

Returns:

Type Description
KT

The wrapped Some value.

Raises:

Type Description
UnwrapException

Raise an exception if the value is a None.

Examples:

1
2
3
4
5
6
7
x: Option[str] = Option.some("air")
assert x.unwrap() == "air"
x: Option[str] = Option.none()
try:
    x.unwrap()
except UnwrapException as e:
    assert str(e) == 'OptionError: call `Option.unwrap` on an `Option::None` object'

unwrap_or(default) abstractmethod

Returns the contained Some value or a provided default.

Arguments passed to unwrap_or are eagerly evaluated.
If you are passing the result of a function call, it is recommended to use unwrap_or_else, which is lazily evaluated.

Parameters:

Name Type Description Default
default KT

The default value.

required

Returns:

Type Description
KT

The contained Some value or a provided default.

Examples:

assert Option.some("car").unwrap_or("bike") == "car"
assert Option.none().unwrap_or("bike") == "bike"

unwrap_or_else(func) abstractmethod

Returns the contained Some value or computes it from a callable object.

Parameters:

Name Type Description Default
func Callable[[], KT]

A callable object to compute.

required

Examples:

1
2
3
k = 10
assert Option.some(4).unwrap_or_else(lambda: 2 * k) == 4
assert Option.none().unwrap_or_else(lambda: 2 * k) == 20

unwrap_unchecked() abstractmethod

Returns the contained value. If self is an Option::None, this will return Python's None directly.

This is the same as Option.to_nullable(). However, this function's signature is -> KT instead of Optional[KT].

unzip()

Unzips an option containing a tuple of two options.

If self is Some((a, b)) this method returns (Some(a), Some(b)). Otherwise, (None, None) is returned.

Examples:

assert Option.some((1, 'hi')).unzip() == (Option.some(1), Option.some('hi'))
assert Option.none().unzip() == (Option.none(), Option.none())

zip(other) abstractmethod

Zips self with another Option.

If self is Some(s) and other is Some(o), this method returns Some((s, o)). Otherwise, None is returned.

Examples:

assert Option.some(1).zip(Option.some('hi')) == Option.some((1, 'hi'))
assert Option.some(1).zip(Option.none()) == Option.none()

zip_with(other, func) abstractmethod

Zips self and another Option with a callable object.

If self is Some(s) and other is Some(o), this method returns Some(f(s, o)). Otherwise, None is returned.

Examples:

1
2
3
4
5
6
def make_point(x, y):
    return Option.some({"x": x, "y": y})

assert Option.some(2)
    .zip_with(Option.some(4), lambda x: make_point(*x)) == Option.some({ "x": 2, "y": 4})
assert Option.some(2).zip_with(Option.none(), lambda x: make_point(*x)) == Option.none()