- class rusttypes.option.Option¶
Bases:
ABC,Generic[T]Option type that represents an optional value.
Variants:
Some(T): Some value of typeT.Nil: No value.
- abstract and_(optb: Option[U]) Option[U]¶
Returns
Nilif the option isNil, otherwise returnsoptb.Arguments passed to
and_are eagerly evaluated; if you are passing the result of a function call, it is recommended to useand_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,Nilotherwise.- 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
Nilif the option isNil, otherwise callsfwith 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_thenlike 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
Optionto an PythonOptional- Returns:
The contained value or
Noneif theOptionisNil.- Return type:
Optional[T]
Examples:
>>> Some(1).as_optional() 1 >>> Nil.as_optional() None
- abstract expect(msg: str) T¶
Returns the contained
Somevalue.- 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
Nilif the option isNil, otherwise callspredicatewith the wrapped value and returns:Some(val)ifpredicatereturnsTrue(wherevalis the wrapped value), andNilifpredicatereturnsFalse.
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
predicateto 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
filterlike 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]]toOption[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
valueinto the option if it isNil, 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 containsSome.- 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 theDefaulttrait of the typeT.- 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
Tdoes not implement theDefaulttrait.
Examples
Lets assume the following dataclass that implements the
Defaulttrait: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_defaultlike 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
finto the option if it isNil, 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
valueinto 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 containsSome.- 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
Optionitself.- Return type:
Option[T]
Examples:
>>> Some(1).inspect(print) 1 Some(1) >>> Nil.inspect(print) Nil
- abstract is_nil() bool¶
Returns
trueif the option is aNilvalue. Equal in function to boolean castnot bool(...).- Returns:
Trueif the option is aNilvalue,Falseotherwise.- Return type:
bool
Examples:
>>> Some(1).is_nil() False >>> Nil.is_nil() True
- abstract is_some() bool¶
Returns
trueif the option is aSomevalue. Equal in function to boolean castbool(...).- Returns:
Trueif the option is aSomevalue,Falseotherwise.- 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
Someand the value inside of it matches a predicate.- Parameters:
f (Callable[[T], bool]) – The predicate to match the value against.
- Returns:
Trueif the option is aSomeand the value matches the predicate,Falseotherwise.- 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]toOption[U]by applying a function to a contained value (ifSome) or returnsNil(ifNil).- 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 (ifSome).Arguments passed to
map_orare eagerly evaluated; if you are passing the result of a function call, it is recommended to usemap_or_else, which is lazily evaluated.- Parameters:
default (U) – The default value to return if the
OptionisNil.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 (ifSome).- 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 aResult[T, E], mappingSome(v)toOk(v)andNiltoErr(err).Arguments passed to
ok_orare eagerly evaluated; if you are passing the result of a function call, it is recommended to useok_or_else, which is lazily evaluated.- Parameters:
err (E) – The error value to use if the
OptionisNil.- 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 aResult[T, E], mappingSome(v)toOk(v)andNiltoErr(f()).- Parameters:
f (Callable[[], E]) – The closure to compute the error value if the
OptionisNil.- 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 useor_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
fand 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
nobodyandvikings:def nobody() -> Option[str]: return Nil def vikings() -> Option[str]: return Some("vikings")
You can now use
or_elselike 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
Somein 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:
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
Niland should be written to the variable from which this function is called if no function chaining is used.Examples:
>>> x = Some(1) >>> x, y = x.take() >>> x Nil >>> y Some(1)
- abstract transpose() Result[Option[T], Any]¶
Transposes an
Optionof aResultinto aResultof anOption.Nilwill be mapped toOk(Nil).Some(Ok(_))andSome(Err(_))will be mapped toOk(Some(_))andErr(_).- Returns:
The transposed result.
- Return type:
- 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
Somevalue.Because this function may throw a RuntimeError, its use is generally discouraged. Instead, prefer to handle the
Nilcase explicitly, or callunwrap_or,unwrap_or_else, orunwrap_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
Somevalue or a provided default.Arguments passed to
unwrap_orare eagerly evaluated; if you are passing the result of a function call, it is recommended to useunwrap_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 typet, which must implement theDefaulttrait.- 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
Defaulttrait: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_defaultlike 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
Somevalue 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
Somevalue.- 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:
- 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
Someif exactly one ofself,optbisSome, otherwise returnsNil.- Parameters:
optb (Option[T]) – The other option to compare with.
- Returns:
Someif exactly one ofself,optbisSome, otherwiseNil.- 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
selfwith anotherOption.If
selfisSome(s)andotherisSome(o), this method returnsSome((s, o)). Otherwise,Nilis 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
selfand anotherOptionwith functionf.If
selfisSome(s)andotherisSome(o), this method returnsSome((s, o)). Otherwise,Nilis 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_withlike 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