Result
Bases: ,
Result[T, E] is the type used for returning and propagating errors.
It is a class that can represent two variants, Ok[T], representing success and containing a value, and Err[E], representing error and containing an error value.
Functions return Result whenever errors are expected and recoverable.
For example, I/O or web requests can fail for many reasons, and using Result forces the caller to handle the possibility of failure.
This is directly inspired by Rust's Result type, and provides similar functionality for error handling in Python.
and_(res)
Returns res if the result is Ok, otherwise returns the Err value.
This is often used for chaining operations that might fail.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
res
|
|
The result to return if the original result is |
required |
Returns:
| Type | Description |
|---|---|
|
Result[U, E]: |
Example:
>>> import pyochain as pc
>>> x = pc.Ok(2)
>>> y = pc.Err("late error")
>>> x.and_(y)
Err('late error')
>>> x = pc.Err("early error")
>>> y = pc.Ok("foo")
>>> x.and_(y)
Err('early error')
>>> x = pc.Err("not a 2")
>>> y = pc.Err("late error")
>>> x.and_(y)
Err('not a 2')
>>> x = pc.Ok(2)
>>> y = pc.Ok("different result type")
>>> x.and_(y)
Ok('different result type')
and_then(fn, *args, **kwargs)
Calls a function if the result is Ok, otherwise returns the Err value.
This is often used for chaining operations that might fail.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
|
The function to call with the |
required |
*args
|
|
Additional positional arguments to pass to fn. |
()
|
**kwargs
|
|
Additional keyword arguments to pass to fn. |
{}
|
Returns:
| Type | Description |
|---|---|
|
Result[R, E]: The result of the function if |
Example:
>>> import pyochain as pc
>>> def to_str(x: int) -> Result[str, str]:
... return pc.Ok(str(x))
>>> pc.Ok(2).and_then(to_str)
Ok('2')
>>> pc.Err("error").and_then(to_str)
Err('error')
and_then_star(func)
and_then_star(
func: Callable[[Any], Result[R, E]],
) -> Result[R, E]
and_then_star(
func: Callable[[T1, T2], Result[R, E]],
) -> Result[R, E]
and_then_star(
func: Callable[[T1, T2, T3], Result[R, E]],
) -> Result[R, E]
and_then_star(
func: Callable[[T1, T2, T3, T4], Result[R, E]],
) -> Result[R, E]
and_then_star(
func: Callable[[T1, T2, T3, T4, T5], Result[R, E]],
) -> Result[R, E]
and_then_star(
func: Callable[[T1, T2, T3, T4, T5, T6], Result[R, E]],
) -> Result[R, E]
and_then_star(
func: Callable[
[T1, T2, T3, T4, T5, T6, T7], Result[R, E]
],
) -> Result[R, E]
and_then_star(
func: Callable[
[T1, T2, T3, T4, T5, T6, T7, T8], Result[R, E]
],
) -> Result[R, E]
and_then_star(
func: Callable[
[T1, T2, T3, T4, T5, T6, T7, T8, T9], Result[R, E]
],
) -> Result[R, E]
and_then_star(
func: Callable[
[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10],
Result[R, E],
],
) -> Result[R, E]
Calls a function if the result is Ok, unpacking the tuple.
Done by applying a function to a contained Ok value (which is expected to be a tuple).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
|
The function to call with the unpacked |
required |
Returns:
| Type | Description |
|---|---|
|
Result[R, E]: The result of the function if |
Example:
>>> import pyochain as pc
>>> def to_str(x: int, y: int) -> pc.Result[str, str]:
... return pc.Ok(f"{x},{y}")
>>> pc.Ok((2, 3)).and_then_star(to_str)
Ok('2,3')
>>> pc.Err("error").and_then_star(to_str)
Err('error')
err()
Converts from Result[T, E] to Option[E].
Err(e) becomes Some(e), and Ok(v) becomes None.
Returns:
| Type | Description |
|---|---|
|
Option[E]: An |
Example:
>>> import pyochain as pc
>>> pc.Ok(2).err()
NONE
>>> pc.Err("error").err()
Some('error')
expect(msg)
Returns the contained Ok value.
Raises an exception with a provided message if the value is an Err.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
msg
|
|
The message to include in the exception if the result is |
required |
Returns:
| Name | Type | Description |
|---|---|---|
T |
|
The contained |
Raises:
| Type | Description |
|---|---|
|
If the result is |
Example:
>>> import pyochain as pc
>>> pc.Ok(2).expect("No error")
2
>>> pc.Err("emergency failure").expect("Testing expect")
Traceback (most recent call last):
...
ResultUnwrapError: Testing expect: 'emergency failure'
expect_err(msg)
Returns the contained Err value.
Raises an exception with a provided message if the value is an Ok.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
msg
|
|
The message to include in the exception if the result is |
required |
Returns:
| Name | Type | Description |
|---|---|---|
E |
|
The contained |
Raises:
| Type | Description |
|---|---|
|
If the result is |
Example:
>>> import pyochain as pc
>>> pc.Err("emergency failure").expect_err("Testing expect_err")
'emergency failure'
>>> pc.Ok(10).expect_err("Testing expect_err")
Traceback (most recent call last):
...
ResultUnwrapError: Testing expect_err: expected Err, got Ok(10)
flatten()
Flattens a nested Result.
Converts from Result[Result[T, E], E] to Result[T, E].
Equivalent to calling Result.and_then(lambda x: x), but more convenient when there's no need to process the inner Ok value.
Returns:
| Type | Description |
|---|---|
|
Result[T, E]: The flattened result. |
Example:
>>> import pyochain as pc
>>> nested_ok: pc.Result[pc.Result[int, str], str] = pc.Ok(pc.Ok(2))
>>> nested_ok.flatten()
Ok(2)
>>> nested_err: pc.Result[pc.Result[int, str], str] = pc.Ok(pc.Err("inner error"))
>>> nested_err.flatten()
Err('inner error')
inspect(fn, *args, **kwargs)
Applies a function to the contained Ok value, returning the original Result.
This is primarily useful for debugging or logging, allowing side effects to be
performed on the Ok value without changing the result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
|
Function to apply to the |
required |
*args
|
|
Additional positional arguments to pass to fn. |
()
|
**kwargs
|
|
Additional keyword arguments to pass to fn. |
{}
|
Returns:
| Type | Description |
|---|---|
|
Result[T, E]: The original result, unchanged. |
Example:
>>> import pyochain as pc
>>> seen: list[int] = []
>>> pc.Ok(2).inspect(lambda x: seen.append(x))
Ok(2)
>>> seen
[2]
inspect_err(fn, *args, **kwargs)
Applies a function to the contained Err value, returning the original Result.
This mirrors :meth:inspect but operates on the error value. It is useful for
logging or debugging error paths while keeping the Result unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
|
Function to apply to the |
required |
*args
|
|
Additional positional arguments to pass to fn. |
()
|
**kwargs
|
|
Additional keyword arguments to pass to fn. |
{}
|
Returns:
| Type | Description |
|---|---|
|
Result[T, E]: The original result, unchanged. |
Example:
>>> import pyochain as pc
>>> seen: list[str] = []
>>> pc.Err("oops").inspect_err(lambda e: seen.append(e))
Err('oops')
>>> seen
['oops']
is_err()
Returns True if the result is Err.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
|
|
Example:
>>> import pyochain as pc
>>> x: pc.Result[int, str] = pc.Ok(2)
>>> x.is_err()
False
>>> y: pc.Result[int, str] = pc.Err("Some error message")
>>> y.is_err()
True
is_err_and(pred, *args, **kwargs)
Returns True if the result is Err and the predicate is true for the error value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pred
|
|
Predicate function to apply to the Err value. |
required |
*args
|
|
Additional positional arguments to pass to pred. |
()
|
**kwargs
|
|
Additional keyword arguments to pass to pred. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
|
True if Err and pred(error) is true, False otherwise. |
Example:
>>> import pyochain as pc
>>> pc.Err("foo").is_err_and(lambda e: len(e) == 3)
True
>>> pc.Err("bar").is_err_and(lambda e: e == "baz")
False
>>> pc.Ok(2).is_err_and(lambda e: True)
False
is_ok()
Returns True if the result is Ok.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
|
|
Example:
>>> import pyochain as pc
>>> x: pc.Result[int, str] = pc.Ok(2)
>>> x.is_ok()
True
>>> y: pc.Result[int, str] = pc.Err("Some error message")
>>> y.is_ok()
False
is_ok_and(pred, *args, **kwargs)
Returns True if the result is Ok and the predicate is true for the contained value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pred
|
|
Predicate function to apply to the |
required |
*args
|
|
Additional positional arguments to pass to pred. |
()
|
**kwargs
|
|
Additional keyword arguments to pass to pred. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
|
True if |
Example:
>>> import pyochain as pc
>>> pc.Ok(2).is_ok_and(lambda x: x > 1)
True
>>> pc.Ok(0).is_ok_and(lambda x: x > 1)
False
>>> pc.Err("err").is_ok_and(lambda x: x > 1)
False
iter()
Returns a Iter[T] over the possibly contained value.
The iterator yields one value if the result is Ok, otherwise none.
Returns:
| Type | Description |
|---|---|
|
Iter[T]: An iterator over the |
Example:
>>> import pyochain as pc
>>> pc.Ok(7).iter().next()
Some(7)
>>> pc.Err("nothing!").iter().next()
NONE
map(fn, *args, **kwargs)
Maps a Result[T, E] to Result[U, E].
Done by applying a function to a contained Ok value,
leaving an Err value untouched.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
|
The function to apply to the |
required |
*args
|
|
Additional positional arguments to pass to fn. |
()
|
**kwargs
|
|
Additional keyword arguments to pass to fn. |
{}
|
Returns:
| Type | Description |
|---|---|
|
Result[R, E]: A new |
Example:
>>> import pyochain as pc
>>> pc.Ok(2).map(lambda x: x * 2)
Ok(4)
>>> pc.Err("error").map(lambda x: x * 2)
Err('error')
map_err(fn, *args, **kwargs)
Maps a Result[T, E] to Result[T, R].
Done by applying a function to a contained Err value,
leaving an Ok value untouched.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
|
The function to apply to the |
required |
*args
|
|
Additional positional arguments to pass to fn. |
()
|
**kwargs
|
|
Additional keyword arguments to pass to fn. |
{}
|
Returns:
| Type | Description |
|---|---|
|
Result[T, R]: A new |
Example:
>>> import pyochain as pc
>>> pc.Ok(2).map_err(len)
Ok(2)
>>> pc.Err("foo").map_err(len)
Err(3)
map_or(default, f, *args, **kwargs)
Applies a function to the Ok value if present, otherwise returns the default value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default
|
|
Value to return if the result is Err. |
required |
f
|
|
Function to apply to the |
required |
*args
|
|
Additional positional arguments to pass to f. |
()
|
**kwargs
|
|
Additional keyword arguments to pass to f. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
R |
|
Result of f(value) if Ok, otherwise default. |
Example:
>>> import pyochain as pc
>>> pc.Ok(2).map_or(10, lambda x: x * 2)
4
>>> pc.Err("err").map_or(10, lambda x: x * 2)
10
map_or_else(ok, err)
Maps a Result[T, E] to U.
Done by applying a fallback function to a contained Err value,
or a default function to a contained Ok value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ok
|
|
The function to apply to the |
required |
err
|
|
The function to apply to the |
required |
Returns:
| Name | Type | Description |
|---|---|---|
U |
|
The result of applying the appropriate function. |
Example:
>>> import pyochain as pc
>>> k = 21
>>> pc.Ok("foo").map_or_else(len, lambda e: k * 2)
3
>>> pc.Err("bar").map_or_else(len, lambda e: k * 2)
42
map_star(func)
map_star(func: Callable[[Any], R]) -> Result[R, E]
map_star(func: Callable[[T1, T2], R]) -> Result[R, E]
map_star(func: Callable[[T1, T2, T3], R]) -> Result[R, E]
map_star(
func: Callable[[T1, T2, T3, T4], R],
) -> Result[R, E]
map_star(
func: Callable[[T1, T2, T3, T4, T5], R],
) -> Result[R, E]
map_star(
func: Callable[[T1, T2, T3, T4, T5, T6], R],
) -> Result[R, E]
map_star(
func: Callable[[T1, T2, T3, T4, T5, T6, T7], R],
) -> Result[R, E]
map_star(
func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8], R],
) -> Result[R, E]
map_star(
func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8, T9], R],
) -> Result[R, E]
map_star(
func: Callable[
[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10], R
],
) -> Result[R, E]
Maps a Result[tuple, E] to Result[R, E] by unpacking the tuple.
Done by applying a function to a contained Ok value (which is expected to be a tuple).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
|
The function to apply to the unpacked |
required |
Returns:
| Type | Description |
|---|---|
|
Result[R, E]: A new |
Example:
>>> import pyochain as pc
>>> pc.Ok((2, 3)).map_star(lambda x, y: x + y)
Ok(5)
>>> pc.Err("error").map_star(lambda x, y: x + y)
Err('error')
ok()
Converts from Result[T, E] to Option[T].
Ok(v) becomes Some(v), and Err(e) becomes None.
Returns:
| Type | Description |
|---|---|
|
Option[T]: An |
Example:
>>> import pyochain as pc
>>> pc.Ok(2).ok()
Some(2)
>>> pc.Err("error").ok()
NONE
or_(res)
Returns res if the result is Err, otherwise returns the Ok value of self.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
res
|
|
The result to return if the original result is |
required |
Returns:
| Type | Description |
|---|---|
|
Result[T, F]: The original |
Example:
>>> import pyochain as pc
>>> pc.Ok(2).or_(pc.Err("late error"))
Ok(2)
>>> pc.Err("early error").or_(pc.Ok(2))
Ok(2)
>>> pc.Err("not a 2").or_(pc.Err("late error"))
Err('late error')
>>> pc.Ok(2).or_(pc.Ok(100))
Ok(2)
or_else(fn, *args, **kwargs)
Calls a function if the result is Err, otherwise returns the Ok value.
This is often used for handling errors by trying an alternative operation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
|
The function to call with the |
required |
*args
|
|
Additional positional arguments to pass to fn. |
()
|
**kwargs
|
|
Additional keyword arguments to pass to fn. |
{}
|
Returns:
| Type | Description |
|---|---|
|
Result[T, E]: The original |
Example:
>>> import pyochain as pc
>>> def fallback(e: str) -> Result[int, str]:
... return pc.Ok(len(e))
>>> pc.Ok(2).or_else(fallback)
Ok(2)
>>> pc.Err("foo").or_else(fallback)
Ok(3)
transpose()
Transposes a Result containing an Option into an Option containing a Result.
Can only be called if the inner type is Option[T, E].
Ok(Some(v)) -> Some(Ok(v)), Ok(NONE) -> NONE, Err(e) -> Some(Err(e))
Returns:
| Type | Description |
|---|---|
|
Option[Result[T, E]]: Option containing a Result or NONE. |
Example:
>>> import pyochain as pc
>>> pc.Ok(pc.Some(2)).transpose()
Some(Ok(2))
>>> pc.Ok(pc.NONE).transpose()
NONE
>>> pc.Err("err").transpose()
Some(Err('err'))
unwrap()
Returns the contained Ok value.
Returns:
| Name | Type | Description |
|---|---|---|
T |
|
The contained |
Raises:
| Type | Description |
|---|---|
|
If the result is |
Example:
>>> import pyochain as pc
>>> pc.Ok(2).unwrap()
2
>>> import pyochain as pc
>>> pc.Err("emergency failure").unwrap()
Traceback (most recent call last):
...
ResultUnwrapError: called `unwrap` on an `Err`: 'emergency failure'
unwrap_err()
Returns the contained Err value.
Returns:
| Name | Type | Description |
|---|---|---|
E |
|
The contained |
Raises:
| Type | Description |
|---|---|
|
If the result is |
Example:
>>> import pyochain as pc
>>> pc.Err("emergency failure").unwrap_err()
'emergency failure'
>>> import pyochain as pc
>>> pc.Ok(2).unwrap_err()
Traceback (most recent call last):
...
ResultUnwrapError: called `unwrap_err` on Ok
unwrap_or(default)
Returns the contained Ok value or a provided default.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default
|
|
The value to return if the result is |
required |
Returns:
| Name | Type | Description |
|---|---|---|
T |
|
The contained |
Example:
>>> import pyochain as pc
>>> pc.Ok(2).unwrap_or(10)
2
>>> pc.Err("error").unwrap_or(10)
10
unwrap_or_else(fn, *args, **kwargs)
Returns the contained Ok value or computes it from a function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
|
A function that takes the |
required |
*args
|
|
Additional positional arguments to pass to fn. |
()
|
**kwargs
|
|
Additional keyword arguments to pass to fn. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
T |
|
The contained |
Example:
>>> import pyochain as pc
>>> pc.Ok(2).unwrap_or_else(len)
2
>>> pc.Err("foo").unwrap_or_else(len)
3