- class rusttypes.option.Some(inner: T)¶
Bases:
Option
,Generic
[T
]- and_(optb: Option[U]) Option[U] ¶
Returns
Nil
if 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
,Nil
otherwise.- Return type:
Option[U]
Examples:
>>> Some(1).and_(Some("foo")) Some("foo") >>> Some(1).and_(Nil) Nil >>> Nil.and_(Some(2)) Nil
- and_then(f: Callable[[T], Option[U]]) Option[U] ¶
Returns
Nil
if the option isNil
, otherwise callsf
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
- as_optional() T | None ¶
Converts the
Option
to an PythonOptional
- Returns:
The contained value or
None
if theOption
isNil
.- Return type:
Optional[T]
Examples:
>>> Some(1).as_optional() 1 >>> Nil.as_optional() None
- 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
- filter(predicate: Callable[[T], bool]) Option[T] ¶
Returns
Nil
if the option isNil
, otherwise callspredicate
with the wrapped value and returns:Some(val)
ifpredicate
returnsTrue
(whereval
is the wrapped value), andNil
ifpredicate
returnsFalse
.
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
- 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
- get_or_insert(value: T) Some[T] ¶
Inserts
value
into 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)
- 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 theDefault
trait 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
T
does not implement theDefault
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
- get_or_insert_with(f: Callable[[], T]) Some[T] ¶
Inserts a value computed from
f
into 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)
- inner: T¶
- 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 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)
- 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
- is_nil() bool ¶
Returns
true
if the option is aNil
value. Equal in function to boolean castnot bool(...)
.- Returns:
True
if the option is aNil
value,False
otherwise.- Return type:
bool
Examples:
>>> Some(1).is_nil() False >>> Nil.is_nil() True
- is_some() bool ¶
Returns
true
if the option is aSome
value. Equal in function to boolean castbool(...)
.- Returns:
True
if the option is aSome
value,False
otherwise.- Return type:
bool
Examples:
>>> Some(1).is_some() True >>> Nil.is_some() False
- 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 aSome
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
- 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
- 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_or
are 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
Option
isNil
.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
- 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
- ok_or(err: E) Result[T, E] ¶
Transforms the
Option[T]
into aResult[T, E]
, mappingSome(v)
toOk(v)
andNil
toErr(err)
.Arguments passed to
ok_or
are 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
Option
isNil
.- Returns:
The transformed
Result
.- Return type:
Result[T, E]
Examples:
>>> Some(1).ok_or("Error") Ok(1) >>> Nil.ok_or("Error") Err("Error")
- ok_or_else(f: Callable[[], E]) Result[T, E] ¶
Transforms the
Option[T]
into aResult[T, E]
, mappingSome(v)
toOk(v)
andNil
toErr(f())
.- Parameters:
f (Callable[[], E]) – The closure to compute the error value if the
Option
isNil
.- 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")
- 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
- 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
andvikings
: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
- 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:
Examples:
>>> x = Some(1) >>> x, y = x.replace(2) >>> x Some(2) >>> y Some(1)
- 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.Examples:
>>> x = Some(1) >>> x, y = x.take() >>> x Nil >>> y Some(1)
- transpose() Result[Option[T], Any] ¶
Transposes an
Option
of aResult
into aResult
of anOption
.Nil
will 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)
- 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 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
- 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 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
- 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 theDefault
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
- 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
- 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
- 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
- xor(optb: Option[T]) Option[T] ¶
Returns
Some
if exactly one ofself
,optb
isSome
, otherwise returnsNil
.- Parameters:
optb (Option[T]) – The other option to compare with.
- Returns:
Some
if exactly one ofself
,optb
isSome
, 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
- zip(other: Option[U]) Option[Tuple[T, U]] ¶
Zips
self
with anotherOption
.If
self
isSome(s)
andother
isSome(o)
, this method returnsSome((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
- zip_with(other: Option[U], f: Callable[[T, U], R]) Option[R] ¶
Zips
self
and anotherOption
with functionf
.If
self
isSome(s)
andother
isSome(o)
, this method returnsSome((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