Option[T]

class rusttypes.option.Option

Bases: ABC, Generic[T]

Option type that represents an optional value.

Variants:

  • Some(T): Some value of type T.

  • Nil: No value.

abstract and_(optb: Option[U]) Option[U]

Returns Nil if the option is Nil, otherwise returns optb.

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:

optb (Option[U]) – The other option to return if the current option is Some.

Returns:

The other option if the current option is Some, Nil otherwise.

Return type:

Option[U]

Examples:

>>> Some(1).and_(Some("foo"))
Some("foo")

>>> Some(1).and_(Nil)
Nil

>>> Nil.and_(Some(2))
Nil
abstract and_then(f: Callable[[T], Option[U]]) Option[U]

Returns Nil if the option is Nil, otherwise calls f with the wrapped value and returns the result.

Some languages call this operation flatmap.

Parameters:

f (Callable[[T], Option[U]]) – The function to call with the value if the option is Some.

Returns:

The result of the function call or Nil.

Return type:

Option[U]

Examples

Lets assume the following function is_positive:

import math

def sqrt(x: float) -> Option[float]:
    if x < 0:
        return Nil
    return Some(math.sqrt(x))

You can now use and_then like this:

>>> Some(4).and_then(sqrt)
Some(2)

>>> Some(-1).and_then(sqrt)
Nil

>>> Nil.and_then(sqrt)
Nil
abstract as_optional() T | None

Converts the Option to an Python Optional

Returns:

The contained value or None if the Option is Nil.

Return type:

Optional[T]

Examples:

>>> Some(1).as_optional()
1

>>> Nil.as_optional()
None
abstract expect(msg: str) T

Returns the contained Some value.

Parameters:

msg – The error message to display if the value is a Nil.

Raises:

RuntimeError – with the given message if the value is a Nil.

Returns:

The contained value.

Return type:

T

Examples:

>>> Some(1).expect("Value is None")
1

>>> Nil.expect("Value is None")
RuntimeError: Value is None
abstract filter(predicate: Callable[[T], bool]) Option[T]

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

  • Some(val) if predicate returns True (where val is the wrapped value), and

  • Nil if predicate returns False.

You can imagine the Option[T] being an iterator over one or zero elements. filter() lets you decide which elements to keep.

Parameters:

predicate (Callable[[T], bool]) – The predicate to match the value against.

Returns:

The filtered Option.

Return type:

Option[T]

Examples

Lets assume the following function is_positive:

def is_positive(x: int) -> bool:
    return x > 0

You can now use filter like this:

>>> Some(1).filter(is_positive)
Some(1)

>>> Some(-42).filter(is_positive)
Nil

>>> Nil.filter(is_positive)
Nil
abstract flatten() Option[T]

Converts from Option[Option[T]] to Option[T].

Returns:

The flattened option.

Return type:

Option[T]

Raises:

ValueError – If the inner type is not an Option.

Examples:

>>> Some(Some(1)).flatten()
Some(1)

>>> Some(Nil).flatten()
Nil

>>> Nil.flatten()
ValueError: Can not flatten if .inner is non-option type
abstract get_or_insert(value: T) Some[T]

Inserts value into the option if it is Nil, then returns the (newly created) value, for the function to work properly override the varibale from which this function is called with the return value if no function chaining is used.

See also Option::insert, which updates the value even if the option already contains Some.

Parameters:

value (T) – The value to insert.

Returns:

The (newly created) value.

Return type:

Some[T]

Examples:

>>> x = Nil
>>> x = x.get_or_insert(2)
>>> x
Some(2)

>>> x = Some(1)
>>> x = x.get_or_insert(2)
>>> x
Some(1)
abstract get_or_insert_default(t: Type[T]) Some[T]

Inserts the default value into the option if it is Nil, then returns the (newly created) value, for the function to work properly override the varibale from which this function is called with the return value if no function chaining is used. The default value is retrieved from the Default trait of the type T.

Parameters:

t (Type[T]) – The type to get the default value from.

Returns:

The (newly created) value.

Return type:

Some[T]

Raises:

ValueError – If the type T does not implement the Default trait.

Examples

Lets assume the following dataclass that implements the Default trait:

from dataclasses import dataclass
from typing import TypeVar, Type
from rusttypes.traits import Default

T = TypeVar("T")

@dataclass
class MyType(Default):
    value: int

    @classmethod
    def default(cls: Type[T]) -> T:
        return MyType(42)

You can now use get_or_insert_default like this:

>>> x = Nil
>>> x = x.get_or_insert_default(MyType)
>>> x.value
42

>>> x = Some(MyType(1))
>>> x = x.get_or_insert_default(MyType)
>>> x.value
1
abstract get_or_insert_with(f: Callable[[], T]) Some[T]

Inserts a value computed from f into the option if it is Nil, then returns the (newly created) value, for the function to work properly override the varibale from which this function is called with the return value if no function chaining is used.

Parameters:

f (Callable[[], T]) – The closure to compute the value.

Returns:

The (newly created) value.

Return type:

Some[T]

Examples:

>>> x = Nil
>>> x = x.get_or_insert_with(lambda: 2)
>>> x
Some(2)

>>> x = Some(1)
>>> x = x.get_or_insert_with(lambda: 2)
>>> x
Some(1)
abstract insert(value: T) Some[T]

Inserts value into the option, then returns the (newly created) value, for the function to work properly override the varibale from which this function is called with the return value if no function chaining is used.

If the option already contains a value, the old value is dropped.

See also Option::get_or_insert, which doesn’t update the value if the option already contains Some.

Parameters:

value (T) – The value to insert.

Returns:

The (newly created) value.

Return type:

Some[T]

Examples:

>>> x = Some(1)
>>> x = x.insert(2)
>>> x
Some(2)
abstract inspect(f: Callable[[T], None]) Option[T]

Calls the provided closure with the contained value (if Some).

Parameters:

f (Callable[[T], None]) – The closure to call with the value.

Returns:

The Option itself.

Return type:

Option[T]

Examples:

>>> Some(1).inspect(print)
1
Some(1)

>>> Nil.inspect(print)
Nil
abstract is_nil() bool

Returns true if the option is a Nil value. Equal in function to boolean cast not bool(...).

Returns:

True if the option is a Nil value, False otherwise.

Return type:

bool

Examples:

>>> Some(1).is_nil()
False

>>> Nil.is_nil()
True
abstract is_some() bool

Returns true if the option is a Some value. Equal in function to boolean cast bool(...).

Returns:

True if the option is a Some value, False otherwise.

Return type:

bool

Examples:

>>> Some(1).is_some()
True

>>> Nil.is_some()
False
abstract is_some_and(f: Callable[[T], bool]) bool

Checks if the option is a Some and the value inside of it matches a predicate.

Parameters:

f (Callable[[T], bool]) – The predicate to match the value against.

Returns:

True if the option is a Some and the value matches the predicate, False otherwise.

Return type:

bool

Examples:

>>> Some(1).is_some_and(lambda x: x > 0)
True

>>> Some(0).is_some_and(lambda x: x > 0)
False

>>> Nil.is_some_and(lambda x: x > 0)
False
abstract map(f: Callable[[T], U]) Option[U]

Maps an Option[T] to Option[U] by applying a function to a contained value (if Some) or returns Nil (if Nil).

Parameters:

f (Callable[[T], U]) – The function to apply to the contained value.

Returns:

The mapped Option[U].

Return type:

Option[U]

Examples:

>>> Some(1).map(lambda x: x + 1)
Some(2)

>>> Nil.map(lambda x: x + 1)
Nil
abstract map_or(default: U, f: Callable[[T], U]) U

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

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:
  • default (U) – The default value to return if the Option is Nil.

  • f (Callable[[T], U]) – The function to apply to the contained value.

Returns:

The mapped value or the default value.

Return type:

U

Examples:

>>> Some("foo").map_or(42, lambda v: len(v))
3

>>> Nil.map_or(42, lambda v: len(v))
42
abstract map_or_else(default: Callable[[], U], f: Callable[[T], U]) U

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

Parameters:
  • default (Callable[[], U]) – The closure to compute the default value.

  • f (Callable[[T], U]) – The function to apply to the contained value.

Returns:

The mapped value or the default value.

Return type:

U

Examples:

>>> Some("foo").map_or_else(lambda: 42, lambda v: len(v))
3

>>> Nil.map_or_else(lambda: 42, lambda v: len(v))
42
abstract ok_or(err: E) Result[T, E]

Transforms the Option[T] into a Result[T, E], mapping Some(v) to Ok(v) and Nil 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:

err (E) – The error value to use if the Option is Nil.

Returns:

The transformed Result.

Return type:

Result[T, E]

Examples:

>>> Some(1).ok_or("Error")
Ok(1)

>>> Nil.ok_or("Error")
Err("Error")
abstract ok_or_else(f: Callable[[], E]) Result[T, E]

Transforms the Option[T] into a Result[T, E], mapping Some(v) to Ok(v) and Nil to Err(f()).

Parameters:

f (Callable[[], E]) – The closure to compute the error value if the Option is Nil.

Returns:

The transformed Result.

Return type:

Result[T, E]

Examples:

>>> Some(1).ok_or_else(lambda: "Error")
Ok(1)

>>> Nil.ok_or_else(lambda: "Error")
Err("Error")
abstract or_(optb: Option[T]) Option[T]

Returns the option if it contains a value, otherwise returns optb.

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:

optb (Option[T]) – The other option to return if the current option is Nil.

Returns:

The current option if it is Some, otherwise the other option.

Return type:

Option[T]

Examples:

>>> Some(1).or_(Some(2))
Some(1)

>>> Some(1).or_(Nil)
Some(1)

>>> Nil.or_(Some(2))
Some(2)

>>> Nil.or_(Nil)
Nil
abstract or_else(f: Callable[[], Option[T]]) Option[T]

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

Parameters:

f (Callable[[], Option[T]]) – The closure to compute the default value.

Returns:

The current option if it is Some, otherwise the result of the closure.

Return type:

Option[T]

Examples

Lets assume the following functions nobody and vikings:

def nobody() -> Option[str]:
    return Nil

def vikings() -> Option[str]:
    return Some("vikings")

You can now use or_else like this:

>>> Some("barbarians").or_else(vikings)
Some("barbarians")

>>> Nil.or_else(vikings)
Some("vikings")

>>> Nil.or_else(nobody)
Nil
abstract replace(value: T) Tuple[Option[T], Option[T]]

Replaces the actual value in the option by the value given in parameter, returning the old value if present, leaving a Some in its place. The first value in the tuple is the new value and should be written to the variable from which this function is called if no function chaining is used.

Parameters:

value (T) – The value to insert.

Returns:

A tuple containing the new value and the old value.

Return type:

Tuple[Option[T], Option[T]]

Examples:

>>> x = Some(1)
>>> x, y = x.replace(2)
>>> x
Some(2)
>>> y
Some(1)
abstract take() Tuple[NilType, Option[T]]

Takes the value out of the option, leaving a None in its place. The first value in the tuple is Nil and should be written to the variable from which this function is called if no function chaining is used.

Returns:

A tuple containing Nil and the value.

Return type:

Tuple[NilType, Option[T]]

Examples:

>>> x = Some(1)
>>> x, y = x.take()
>>> x
Nil
>>> y
Some(1)
abstract transpose() Result[Option[T], Any]

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

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

Returns:

The transposed result.

Return type:

Result[Option[T], Any]

Raises:

ValueError – If the inner type is not a Result.

Examples:

>>> Some(Ok(1)).transpose()
Ok(Some(1))

>>> Some(Err("error")).transpose()
Err("error")

>>> Nil.transpose()
Ok(Nil)
abstract unwrap() T

Returns the contained Some value.

Because this function may throw a RuntimeError, its use is generally discouraged. Instead, prefer to handle the Nil case explicitly, or call unwrap_or, unwrap_or_else, or unwrap_or_default.

Returns:

The contained value.

Return type:

T

Raises:

RuntimeError – if the value is a None.

Examples:

>>> Some(1).unwrap()
1

>>> Nil.unwrap()
RuntimeError: Called unwrap on a Nil value
abstract unwrap_or(default: T) T

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.

Returns:

The contained value or the default value.

Return type:

T

Examples:

>>> Some(1).unwrap_or(2)
1

>>> Nil.unwrap_or(2)
2
abstract unwrap_or_default(t: Type[T]) T

Returns the contained Some value or a default.

Consumes the self argument then, if Some, returns the contained value, otherwise if Nil, returns the default value for that type t, which must implement the Default trait.

Parameters:

t (Type[T]) – The type to get the default value from.

Returns:

The contained value or the default value.

Return type:

T

Examples

Lets assume the following dataclass that implements the Default trait:

from __future__ import annotations
from dataclasses import dataclass
from rusttypes.traits import Default

T = TypeVar("T")

@dataclass
class MyType(Default):
    value: int

    @staticmethod
    def default() -> MyType:
        return MyType(42)

You can now use unwrap_or_default like this:

>>> x = Some(MyType(1))
>>> x.unwrap_or_default(MyType).value
1

>>> Nil.unwrap_or_default(MyType).value
42
abstract unwrap_or_else(f: Callable[[], T]) T

Returns the contained Some value or computes it from a closure.

Parameters:

f (Callable[[], T]) – The closure to compute the default value.

Returns:

The contained value or the default value.

Return type:

T

Examples:

>>> Some(1).unwrap_or_else(lambda: 2)
1

>>> Nil.unwrap_or_else(lambda: 2)
2
abstract unwrap_unchecked() T

Returns the contained Some value.

Returns:

The contained value.

Return type:

T

Raises:

RuntimeError – if the value is a Nil.

Examples:

>>> Some(1).unwrap_unchecked()
1

>>> Nil.unwrap_unchecked()
RuntimeError: Called unwrap_unchecked on a Nil value
abstract unzip() Tuple[Option[Any], Option[Any]]

Unzips an option containing a tuple of two options.

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

Returns:

The unzipped options.

Return type:

Tuple[Option[Any], Option[Any]]

Raises:

ValueError – If the inner type is not a tuplelike of length 2.

Examples:

>>> Some((1, "foo")).unzip()
(Some(1), Some("foo"))

>>> Nil.unzip()
(Nil, Nil)

>>> Some((1, "foo", 3)).unzip()
ValueError: Can not unzip tuple with more/less than 2 elements
abstract xor(optb: Option[T]) Option[T]

Returns Some if exactly one of self, optb is Some, otherwise returns Nil.

Parameters:

optb (Option[T]) – The other option to compare with.

Returns:

Some if exactly one of self, optb is Some, otherwise Nil.

Return type:

Option[T]

Examples:

>>> Some(1).xor(Some(2))
Nil

>>> Some(1).xor(Nil)
Some(1)

>>> Nil.xor(Some(2))
Some(2)

>>> Nil.xor(Nil)
Nil
abstract zip(other: Option[U]) Option[Tuple[T, U]]

Zips self with another Option.

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

Parameters:

other (Option[U]) – The other option to zip with.

Returns:

The zipped option.

Return type:

Option[Tuple[T, U]]

Examples:

>>> Some(1).zip(Some("foo"))
Some((1, "foo"))

>>> Some(1).zip(Nil)
Nil

>>> Nil.zip(Some("foo"))
Nil
abstract zip_with(other: Option[U], f: Callable[[T, U], R]) Option[R]

Zips self and another Option with function f.

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

Parameters:
  • other (Option[U]) – The other option to zip with.

  • f (Callable[[ T, U ], R]) – The function to apply to the zipped values.

Returns:

The zipped option.

Return type:

Option[R]

Examples

Lets assume the following dataclass Point:

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

You can now use zip_with like this:

>>> Some(1).zip_with(Some(2), Point)
Some(Point(1, 2))

>>> Some(1).zip_with(Nil, Point)
Nil

>>> Nil.zip_with(Some(2), Point)
Nil