rusttypes.result
¶
Classes¶
Members¶
- @rusttypes.result.catch(*exceptions: ~typing.Type[BaseException], map_err: ~typing.Callable[[BaseException], ~rusttypes.result.E] = <function stringify>) Callable[[Callable[[...], Result[T, E]]], Callable[[...], Result[T, E]]] ¶
Catch specified exceptions and return them as
Err
. If no exceptions are specified, catch all exceptions. Use themap_err
function to map the caught exception to the error type of theResult
.- Parameters:
*exceptions (Type[BaseException]) – The exceptions to catch.
map_err (Callable[[BaseException], E]) – The function to map the caught exception to the error type of the
Result
. Defaults torusttypes.misc.stringify
.
- Returns:
Decorator that catches the specified exceptions and returns them as
Err
.- Return type:
Callable[[Callable[…, Result[T, E]]], Callable[…, Result[T, E]]]
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
:@catch(ValueError) def parse_int(s: str) -> Result[int, str]: return Ok(int(s))
You can now use the function and handle the error case:
>>> parse_int("42") Ok(42) >>> parse_int("foo") Err("invalid literal for int() with base 10: 'foo'")
- @rusttypes.result.try_guard(fn: Callable[[...], Result[T, E]]) Callable[[...], Result[T, E]] ¶
Bubble up
Err
that are thrown inside the function. If anErr
is thrown, it is returned as is. This is useful in combination with theResult::try_
method.Works in conjunction with the
Result::try_
function similar to the?
operator in Rust.- Parameters:
fn (Callable[..., Result[T, E]]) – The function to wrap.
- Returns:
Wrapped function that bubbles up
Err
.- Return type:
Callable[…, Result[T, E]]
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'")