Skip to content

Result#

A container that holds either a success or a failure.

See Result and Either.

A Result has two possible states, Ok or Err. Ok means a successful value is present, and Err means a failure value is present.

This module also provides a caught decorator, which wraps a partial function to a total function returning a Result.

The Result class, and the ok, err, and caught functions are exposed in the package namespace.

Rationale#

Python raise is easily missed, since the gradual typing system does not support checked exceptions. An alternative is to return nullable error flags, which is cumbersome to work with.

Implementation#

Result's APIs are based on the Rust Result, and the comparison table is provided below.

Reference Result Counterpart
and and_
and_then
as_deref
as_deref_mut
as_mut
as_ref
cloned
copied
err
expect
expect_err
flatten
inspect tap
inspect_err tap_err
into_err
into_ok
is_err
is_err_and
is_ok
is_ok_and
iter
iter_mut
map
map_err
map_or
map_or_default
map_or_else
ok
or or_
or_else
transpose
unwrap
unwrap_err
unwrap_err_unchecked
unwrap_or
unwrap_or_default
unwrap_or_else
unwrap_unchecked

Result #

A container that holds either a success or a failure. See module-level documentation for more details.

This class is exposed in the package namespace.

and_(other) #

If the value is Ok, return a shallow copy of the other Result. Otherwise, return a new Err of type Result[T, E].

and_then(f) #

If the value is Ok, apply a function that maps the inner value to a Result[U, E] value. Otherwise, return Err of type Result[U, E].

apply(f) #

Implementation of Applicative.apply. Applies the callable wrapped within a Result to the inner value, if both are Ok.

bind(f) #

Implementation of Monad.bind. Alias of and_then.

err() #

Convert a Result[T, E] to a Maybe[E].

expect(message) #

Unwrap the inner Ok value, if any. Otherwise, raise a ValueError with a custom message.

expect_err(message) #

Unwrap the inner Err value, if any. Otherwise, raise a ValueError with a custom message.

flatten() #

Flatten a nested Result (Result[Result[T, E], E]) value for one level (Result[T, E]).

is_err() #

Check if the value is an Err.

is_err_and(p) #

Check if the value is an Err and satisfies the predicate.

is_ok() #

Check if the value is an Ok.

is_ok_and(p) #

Check if the value is an Ok and satisfies the predicate.

make_err(val) classmethod #

Construct an Err value.

make_ok(val) classmethod #

Construct an Ok value.

map(f) #

Map a Result[T, E] to Result[U, E] by applying a function to a contained Ok value, leaving an Err value untouched.

map_err(f) #

Map a Result[T, E] to Result[T, F] by applying a function to a contained Err value, leaving an Ok value untouched.

map_or(default, f) #

Apply a function to a contained Ok value, or return a provided default value.

map_or_else(d, f) #

Map a Result[T, E] to U by applying a function to a contained Ok value, or a fallback function to a contained Err value.

ok() #

Convert a Result[T, E] to a Maybe[T].

or_(other) #

If the value is Err, return a shallow copy of the other Result. Otherwise, return a new Ok of type Result[T, F].

or_else(f) #

Return a shallow copy of the Result if it contains an Ok value, otherwise call a function to get a result.

pure(x) classmethod #

Implementation of Applicative.pure, which is equivalent to Result.make_ok.

tap(f) #

Call a function with the contained Ok value if it exists.

Unlike Result::inspect, this method does not require the function to return None.

some_ok = ok(5)
some_err = err("error")
some_ok.tap(print)  # prints: 5
some_err.tap(print)  # prints nothing

tap_err(f) #

Call a function with the contained Err value if it exists.

throw() #

Raise the contained exception if it is an Err. Otherwise, return the inner Ok value.

transpose() #

Transpose a Result of a Maybe into a Maybe of a Result. Result[Maybe[T], E] -> Maybe[Result[T, E]]

unwrap() #

Unwrap the inner Ok value, if any. Otherwise, raise a ValueError.

unwrap_err() #

Unwrap the inner Err value, if any. Otherwise, raise a ValueError.

unwrap_err_unchecked() #

Return the inner Err value without checking if it is an Err.

unwrap_or(default) #

Unwrap the inner Ok value, or return a default value if contains an Err.

unwrap_or_else(f) #

Unwrap the inner Ok value, or return a value computed by a function if contains an Err.

unwrap_unchecked() #

Return the inner value without checking if it is an Ok or Err.

ok #

Construct an Ok value.

This function is exposed in the package namespace.

some_ok = ok(42)

match some_ok:
    case ok(value):
        print(f"Got an Ok with value: {value}")
    case err(error):
        print(f"Got an Err with error: {error}")

# Output: Got an Ok with value: 42

err #

Construct an Err value.

This function is exposed in the package namespace.

some_err = err("Something went wrong")
match some_err:
    case ok(value):
        print(f"Got an Ok with value: {value}")
    case err(error):
        print(f"Got an Err with error: {error}")

# Output: Got an Err with error: Something went wrong

caught #

A decorator that wraps a partial function to a total function returning a Result.

It supports multiple usages:

  • Use as a decorator without arguments (@caught) to catch all exceptions.
  • Use as a decorator with specific exception types (either type union @caught(ExceptionA | ExceptionB) or args @caught(ExceptionA, ExceptionB)) to catch only those exceptions.
  • Use as a higher-order function by passing the target function (caught(func)) to catch all exceptions.
  • Use as a higher-order function with specific exception types as args (caught(func, ExceptionA, ExceptionB)) to catch only those exceptions.
  • Use generic syntax to provide type hints (@caught[ExceptionA], @caught[ExceptionA](), caught[ExceptionA]()), without affecting runtime behavior.

This function is exposed in the package namespace.

Usage
@caught(ZeroDivisionError)
def divide(a: float, b: float) -> float:
    return a / b

divide(4, 2)  # Ok(2.0)
divide(4, 0)  # Err(ZeroDivisionError)