Result[T, E]

class rusttypes.result.Result

Bases: ABC, Generic[T, E]

Result type that represents either a successful value or an error. The Result type is a sum type that can be either an Ok or an Err. The Ok variant holds the successful value, while the Err variant holds the error value. The Result type is used to handle errors in a functional way. The Result type is inspired by Rust’s Result type.

Variants:

  • Ok(T): Represents a successful value T.

  • Err(E): Represents an error value of type E.

abstract and_(res: Result[U, E]) Result[U, E]

Returns res if the result is Ok, otherwise returns the Err value of self.

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:

res (Result[U, E]) – The result to return if the result is Ok.

Returns:

res if the result is Ok, otherwise the Err value of self.

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 op if the result is Ok, otherwise returns the Err value of self.

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 the Err value of self.

Return type:

Result[U, E]

Examples

Lets assume we have a function that squares and then stringifies an float, that can fail if the float is greater than 1_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_then method 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] to Option[E].

Converts self into an Option[E] and discarding the success value, if any.

Returns:

Some(E) if the result is Err, otherwise Nil.

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 Ok value..

Because this function may panic, its use is generally discouraged. Instead, prefer to use pattern matching and handle the Err case explicitly, or call unwrap_or, unwrap_or_else, or unwrap_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 Err value.

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 True if the result is Err. Is the inverse of Result::is_ok.

Returns:

True if the result is Err, otherwise False.

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 True if the result is Err and the value inside of it matches a predicate.

Parameters:

f (Callable[[E], bool]) – The predicate to match against.

Returns:

True if the result is Err and the value inside of it matches the predicate, otherwise False.

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 True if the Result is Ok.

Returns:

True if the Result is Ok, otherwise False.

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 True if the result is Ok and the value inside of it matches a predicate.

Parameters:

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

Returns:

True if the result is Ok and the value inside of it matches the predicate, otherwise False.

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] to Result[U, E] by applying a function to a contained Ok value, leaving an Err value 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 is Ok, otherwise Err(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] to Result[T, F] by applying a function to a contained Err value, leaving an Ok value 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 is Ok, otherwise Err(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 (if Ok).

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 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] to U by applying fallback function default to a contained Err value, or function f to a contained Ok value.

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] to Option[T].

Converts self into an Option[T] and discarding the error, if any.

Returns:

Some(T) if the result is Ok, otherwise Nil.

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 res if the result is Err, otherwise returns the Ok value of self.

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:

res (Result[T, F]) – The result to return if the result is Err.

Returns:

res if the result is Err, otherwise the Ok value of self.

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 op if the result is Err, otherwise returns the Ok value of self.

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 the Ok value of self.

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_else method 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 contained Err value as ResultException. Should only be used in combination with the @try_guard decorator.

Works in conjunction with the @try_guard decorator 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 Ok value.

Because this function may panic, its use is generally discouraged. Instead, prefer to use pattern matching and handle the Err case explicitly, or call unwrap_or, unwrap_or_else, or unwrap_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 Err value.

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 Err value.

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 Ok 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.

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 Ok value or a default. t has to be a type that implements the Default trait.

If Ok, returns the contained value, otherwise if Err, returns the default value for that type.

Parameters:

t (Type[T]) – The type that implements the Default trait.

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 Default trait:

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_default method:

>>> 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 Ok value 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 Ok value.

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