- class rusttypes.result.Result¶
Bases:
ABC,Generic[T,E]Result type that represents either a successful value or an error. The
Resulttype is a sum type that can be either anOkor anErr. TheOkvariant holds the successful value, while theErrvariant holds the error value. TheResulttype is used to handle errors in a functional way. TheResulttype is inspired by Rust’sResulttype.Variants:
Ok(T): Represents a successful valueT.Err(E): Represents an error value of typeE.
- abstract and_(res: Result[U, E]) Result[U, E]¶
Returns
resif the result isOk, otherwise returns theErrvalue ofself.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:
res (Result[U, E]) – The result to return if the result is
Ok.- Returns:
resif the result isOk, otherwise theErrvalue ofself.- Return type:
Result[U, E]
Examples:
>>> Ok(42).and_(Ok(21)) Ok(21) >>> Ok(42).and_(Err("Some error message")) Err("Some error message") >>> Err("Some error message").and_(Ok(21)) Err("Some error message") >>> Err("Some error message").and_(Err("Another error message")) Err("Some error message")
- abstract and_then(op: Callable[[T], Result[U, E]]) Result[U, E]¶
Calls
opif the result isOk, otherwise returns theErrvalue ofself.This function can be used for control flow based on Result values.
- Parameters:
op (Callable[[T], Result[U, E]]) – The function to call if the result is
Ok.- Returns:
The result of the function if the result is
Ok, otherwise theErrvalue ofself.- Return type:
Result[U, E]
Examples
Lets assume we have a function that squares and then stringifies an
float, that can fail if thefloatis greater than1_000_000:import math def sq_and_stringify(x: int) -> Result[str, str]: if math.abs(x) >= 1_000_000: return Err("Number too large") return Ok(str(x * x))
Now we can use the
and_thenmethod to chain the function calls:>>> Ok(42).and_then(sq_and_stringify) Ok("1764") >>> Ok(1_000_000).and_then(sq_and_stringify) Err("Number too large")
- abstract err() Option[E]¶
Converts from
Result[T, E]toOption[E].Converts
selfinto anOption[E]and discarding the success value, if any.- Returns:
Some(E)if the result isErr, otherwiseNil.- Return type:
Option[E]
Examples:
>>> Ok(42).err() Nil >>> Err("Some error message").err() Some("Some error message")
- abstract expect(msg: str) T¶
Returns the contained
Okvalue..Because this function may panic, its use is generally discouraged. Instead, prefer to use pattern matching and handle the
Errcase explicitly, or callunwrap_or,unwrap_or_else, orunwrap_or_default.- Parameters:
msg (str) – The message to display in case of a panic.
- Returns:
The contained value if the result is
Ok.- Return type:
T
- Raises:
RuntimeError – If the result is
Err.
Examples:
>>> Ok(42).expect("This should not panic") 42 >>> Err("Some error message").expect("This should panic") RuntimeError: This should panic
- abstract expect_err(msg: str) E¶
Returns the contained
Errvalue.- Parameters:
msg (str) – The message to display in case of a panic.
- Returns:
The contained value if the result is
Err.- Return type:
E
- Raises:
RuntimeError – If the result is
Ok.
Examples:
>>> Ok(42).expect_err("This should panic") RuntimeError: This should panic >>> Err("Some error message").expect_err("This should not panic") Some error message
- abstract inspect(op: Callable[[T], None]) Result[T, E]¶
Calls the provided closure with a copy of the contained value (if
Ok).- Parameters:
op (Callable[[T], None]) – The closure to call with the contained value.
- Returns:
The result itself.
- Return type:
Result[T, E]
Examples:
>>> Ok(42).inspect(print) 42 Ok(42) >>> Err("Some error message").inspect(print) Err("Some error message")
- abstract inspect_err(op: Callable[[E], None]) Result[T, E]¶
Calls the provided closure with a copy of the contained error (if
Err).- Parameters:
op (Callable[[E], None]) – The closure to call with the contained error.
- Returns:
The result itself.
- Return type:
Result[T, E]
Examples:
>>> Ok(42).inspect_err(print) Ok(42) >>> Err("Some error message").inspect_err(print) Some error message Err("Some error message")
- abstract is_err() bool¶
Returns
Trueif the result isErr. Is the inverse ofResult::is_ok.- Returns:
Trueif the result isErr, otherwiseFalse.- Return type:
bool
Examples:
>>> Ok(42).is_err() False >>> Err("Some error message").is_err() True
- abstract is_err_and(f: Callable[[E], bool]) bool¶
Returns
Trueif the result isErrand the value inside of it matches a predicate.- Parameters:
f (Callable[[E], bool]) – The predicate to match against.
- Returns:
Trueif the result isErrand the value inside of it matches the predicate, otherwiseFalse.- Return type:
bool
Examples:
>>> Ok(42).is_err_and(lambda x: isinstance(x, str)) False >>> Err("Some error message").is_err_and(lambda x: isinstance(x, str)) True
- abstract is_ok() bool¶
Returns
Trueif theResultisOk.- Returns:
Trueif theResultisOk, otherwiseFalse.- Return type:
bool
Examples:
>>> Ok(42).is_ok() True >>> Err("Some error message").is_ok() False
- abstract is_ok_and(f: Callable[[T], bool]) bool¶
Returns
Trueif the result isOkand the value inside of it matches a predicate.- Parameters:
f (Callable[[T], bool]) – The predicate to match against.
- Returns:
Trueif the result isOkand the value inside of it matches the predicate, otherwiseFalse.- Return type:
bool
Examples:
>>> Ok(42).is_ok_and(lambda x: x > 0) True >>> Ok(-42).is_ok_and(lambda x: x > 0) False >>> Err("Some error message").is_ok_and(lambda x: x > 0) False
- abstract map(op: Callable[[T], U]) Result[U, E]¶
Maps a
Result[T, E]toResult[U, E]by applying a function to a containedOkvalue, leaving anErrvalue untouched.This function can be used to compose the results of two functions.
- Parameters:
op (Callable[[T], U]) – The function to apply to the contained value.
- Returns:
Ok(U)if the result isOk, otherwiseErr(E).- Return type:
Result[U, E]
Examples:
>>> Ok(21).map(lambda x: x * 2) Ok(42) >>> Err("Some error message").map(lambda x: x * 2) Err("Some error message")
- abstract map_err(op: Callable[[E], F]) Result[T, F]¶
Maps a
Result[T, E]toResult[T, F]by applying a function to a containedErrvalue, leaving anOkvalue untouched.This function can be used to pass through a successful result while handling an error.
- Parameters:
op (Callable[[E], F]) – The function to apply to the contained value.
- Returns:
Ok(T)if the result isOk, otherwiseErr(F).- Return type:
Result[T, F]
Examples:
>>> Ok(42).map_err(lambda e: f"Error: {e}")) Ok(42) >>> Err(42).map_err(lambda e: f"Error: {e}") Err("Error: 42")
- abstract map_or(default: U, f: Callable[[T], U]) U¶
Returns the provided default (if
Err), or applies a function to the contained value (ifOk).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 value to return if the result is
Err.f (Callable[[T], U]) – The function to apply to the contained value if the result is
Ok.
- Returns:
The result of the function if the result is
Ok, otherwise the default value.- Return type:
U
Examples:
>>> Ok(21).map_or(0, lambda x: x * 2) 42 >>> Err("Some error message").map_or(0, lambda x: x * 2) 0
- abstract map_or_else(default: Callable[[E], U], f: Callable[[T], U]) U¶
Maps a
Result[T, E]toUby applying fallback functiondefaultto a containedErrvalue, or functionfto a containedOkvalue.This function can be used to unpack a successful result while handling an error.
- Parameters:
default (Callable[[E], U]) – The function to apply to the contained value if the result is
Err.f (Callable[[T], U]) – The function to apply to the contained value if the result is
Ok.
- Returns:
The result of the function if the result is
Ok, otherwise the default value.- Return type:
U
Examples:
>>> Ok(21).map_or_else(lambda e: 0, lambda x: x * 2) 42 >>> Err("Some error message").map_or_else(lambda e: 0, lambda x: x * 2) 0
- abstract ok() Option[T]¶
Converts from
Result[T, E]toOption[T].Converts
selfinto anOption[T]and discarding the error, if any.- Returns:
Some(T)if the result isOk, otherwiseNil.- Return type:
Option[T]
Examples:
>>> Ok(42).ok() Some(42) >>> Err("Some error message").ok() Nil
- abstract or_(res: Result[T, F]) Result[T, F]¶
Returns
resif the result isErr, otherwise returns theOkvalue ofself.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:
res (Result[T, F]) – The result to return if the result is
Err.- Returns:
resif the result isErr, otherwise theOkvalue ofself.- Return type:
Result[T, F]
Examples:
>>> Ok(42).or_(Ok(21)) Ok(42) >>> Ok(42).or_(Err("Some error message")) Ok(42) >>> Err("Some error message").or_(Ok(21)) Ok(21) >>> Err("Some error message").or_(Err("Another error message")) Err("Another error message")
- abstract or_else(op: Callable[[E], Result[T, F]]) Result[T, F]¶
Calls
opif the result isErr, otherwise returns theOkvalue ofself.This function can be used for control flow based on result values.
- Parameters:
op (Callable[[E], Result[T, F]]) – The function to call if the result is
Err.- Returns:
The result of the function if the result is
Err, otherwise theOkvalue ofself.- Return type:
Result[T, F]
Examples
Lets assume we have function that squares an int and a function that returns the int as an error:
def sq(x: int) -> Result[int, int]: return Ok(x * x) def err(x: int) -> Result[int, int]: return Err(x)
Now we can use the
or_elsemethod to chain the function calls:>> Ok(2).or_else(sq).or_else(sq) Ok(2) >>> Ok(2).or_else(err).or_else(sq) Ok(2) >>> Err(3).or_else(sq).or_else(err) Ok(9) >>> Err(3).or_else(err).or_else(err) Err(3)
- abstract try_() T¶
Returns the contained
Ok, else raises the containedErrvalue asResultException. Should only be used in combination with the@try_guarddecorator.Works in conjunction with the
@try_guarddecorator similar to the?operator in Rust.- Returns:
The contained value if the result is
Ok.- Return type:
T
- Raises:
ResultException – If the result is
Err.
Examples
Lets say we have a function that parses a string to an integer. If the string is not a valid integer, we want to return an error instead of raising a
ValueError. Now we want to parse an array of integers and return an error if one of the integers is invalid:@catch(ValueError) def parse_int(s: str) -> Result[int, str]: return Ok(int(s)) @try_guard def parse_int_array(arr: str) -> Result[List[int], str]: return Ok([parse_int(s).try_() for s in arr.split()])
You can now use the function and handle the error case:
>>> parse_int_array("42 21 1337") Ok([42, 21, 1337]) >>> parse_int_array("42 foo 1337") Err("invalid literal for int() with base 10: 'foo'")
- abstract unwrap() T¶
Returns the contained
Okvalue.Because this function may panic, its use is generally discouraged. Instead, prefer to use pattern matching and handle the
Errcase explicitly, or callunwrap_or,unwrap_or_else, orunwrap_or_default.- Returns:
The contained value if the result is
Ok.- Return type:
T
- Raises:
RuntimeError – If the result is
Err.
Examples:
>>> Ok(42).unwrap() 42 >>> Err("Some error message").unwrap() RuntimeError: Called unwrap on Err
- abstract unwrap_err() E¶
Returns the contained
Errvalue.- Returns:
The contained value if the result is
Err.- Return type:
E
- Raises:
RuntimeError – If the result is
Ok.
Examples:
>>> Ok(42).unwrap_err() RuntimeError: Called unwrap_err on Ok >>> Err("Some error message").unwrap_err() "Some error message"
- abstract unwrap_err_unchecked() E¶
Retruns the contained
Errvalue.- Returns:
The contained value if the result is
Err.- Return type:
E
- Raises:
RuntimeError – If the result is
Ok.
Examples:
>>> Ok(42).unwrap_err_unchecked() RuntimeError: Called unwrap_err_unchecked on Ok >>> Err("Some error message").unwrap_err_unchecked() "Some error message"
- abstract unwrap_or(default: T) T¶
Returns the contained
Okvalue 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.- Parameters:
default (T) – The value to return if the result is
Err.- Returns:
The contained value if the result is
Ok, otherwise the default value.- Return type:
T
Examples:
>>> Ok(42).unwrap_or(0) 42 >>> Err("Some error message").unwrap_or(0) 0
- abstract unwrap_or_default(t: Type[T]) T¶
Returns the contained
Okvalue or a default.thas to be a type that implements theDefaulttrait.If
Ok, returns the contained value, otherwise ifErr, returns the default value for that type.- Parameters:
t (Type[T]) – The type that implements the
Defaulttrait.- Returns:
The contained value if the result is
Ok, otherwise the default value of the type.- Return type:
T
Examples
Lets assume we have a type that implements the
Defaulttrait:from __future__ import annotations from dataclasses import dataclass from rusttypes.traits import Default T = TypeVar("T") @dataclass class Foo(Default): x: int @staticmethod def default() -> Foo: return Foo(42)
Now we can use the
unwrap_or_defaultmethod:>>> Ok(Foo(21)).unwrap_or_default(Foo) Foo(21) >>> Err("Some error message").unwrap_or_default(Foo) Foo(42)
- abstract unwrap_or_else(op: Callable[[E], T]) T¶
Returns the contained
Okvalue or computes it from a closure.- Parameters:
op (Callable[[E], T]) – The closure to call if the result is
Err.- Returns:
The contained value if the result is
Ok, otherwise the result of the closure.- Return type:
T
Examples:
>>> Ok(42).unwrap_or_else(lambda e: len(e)) 42 >>> Err("foo").unwrap_or_else(lambda e: len(e)) 3
- abstract unwrap_unchecked() T¶
Returns the contained
Okvalue.- Returns:
The contained value if the result is
Ok.- Return type:
T
- Raises:
RuntimeError – If the result is
Err.
Examples:
>>> Ok(42).unwrap_unchecked() 42 >>> Err("Some error message").unwrap_unchecked() RuntimeError: Called unwrap_unchecked on Err