Skip to content

monad_std.result.Result

Bases: Generic[KT, KE]

An ancestor class of any Result type, inherited by Ok and Err subclasses.

ERR: t.Literal[False] = False class-attribute instance-attribute

The flag for error value. See Result.to_pattern for more information.

OK: t.Literal[True] = True class-attribute instance-attribute

The flag for ok value. See Result.to_pattern for more information.

__add__(other)

Alias self.__value.__add__.

Returns:

Type Description
Result[Any, Any]

If both value are Ok, this will return Ok(self + other). Otherwise, return the first Err.

__bool__()

Returns True if the result is Ok.

__mul__(other)

Alias self.__value.__mul__.

Returns:

Type Description
Result[Any, Any]

If both value are Ok, this will return Ok(self * other). Otherwise, return the first Err.

and_then(op) abstractmethod

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:

Name Type Description Default
op Callable[[KT], Result[U, KE]]

The callable object to execute.

required

Examples:

1
2
3
assert Result.of_ok(2).and_then(lambda n: Result.of_ok(n * 2)) == Result.of_ok(4)
assert Result.of_ok(2).and_then(lambda _: Result.of_err('err')) == Result.of_err('err')
assert Result.of_err('err').and_then(lambda n: Result.of_ok(n * 2)) == Result.of_err('err')

bool_and(res) abstractmethod

Returns res if the result is Ok, otherwise returns the Err value of self. Alias &(__and__).

and is a keyword of Python, so we use bool_and instead.

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:

Name Type Description Default
res Result[U, KE]

Another Result instance.

required

Examples:

1
2
3
4
assert Result.of_ok(2).bool_and(Result.of_err('late error')) == Result.of_err('late error')
assert Result.of_err('early error').bool_and(Result.of_ok(2)) == Result.of_err('early error')
assert Result.of_err('early error').bool_and(Result.of_err('late error')) == Result.of_err('early error')
assert Result.of_ok(2).bool_and(Result.of_ok('another ok')) == Result.of_ok('another ok')

bool_or(res) abstractmethod

Returns res if the result is Err, otherwise returns the Ok value of self. Alias ||(__or__).

or is a keyword of Python, so we use bool_or instead.

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:

Name Type Description Default
res Result[KT, F]

Another Result instance.

required

Examples:

1
2
3
4
assert Result.of_ok(2).bool_or(Result.of_err('late error')) == Result.of_ok(2)
assert Result.of_err('early error').bool_or(Result.of_ok(2)) == Result.of_ok(2)
assert Result.of_err('early error').bool_or(Result.of_err('late error')) == Result.of_err('late error')
assert Result.of_ok(2).bool_or(Result.of_ok(100)) == Result.of_ok(2)

catch(func) staticmethod

Catch a thrown exception from the function.

Parameters:

Name Type Description Default
func Callable[[], T]

A function to catch the thrown exception.

required

Returns:

Type Description
Result[T, Exception]

A Result of either the result of the function or the exception. You can cast the exception manually.

Examples:

1
2
3
4
5
6
7
8
def maybe_error(v: int) -> int:
    if v % 2 == 0:
        return v + 1
    else:
        raise ValueError()

assert Result.catch(lambda: maybe_error(2)) == Result.of_ok(3)
assert isinstance(Result.catch(lambda: maybe_error(3)).unwrap_err(), ValueError)

catch_from(func, *args, **kwargs) staticmethod

Catch a thrown exception from a function call.

Parameters:

Name Type Description Default
func Callable

The function to call

required
*args Any

The arguments passing to func.

()
**kwargs Any

The keyword arguments passing to func.

{}

Returns:

Type Description
Result

A Result of either the result of the function or the exception. You can cast them manually.

Examples:

1
2
3
4
5
6
7
8
def maybe_error(v: int) -> int:
    if v % 2 == 0:
        return v + 1
    else:
        raise ValueError()

assert Result.catch_from(maybe_error, v=2) == Result.of_ok(3)
assert isinstance(Result.catch_from(maybe_error, 3).unwrap_err(), ValueError)

err() abstractmethod

Converts from Result<KT, KE> to Option<KE>.

Converts self into an Option<KE>, and discarding the success value, if any.

Examples:

assert Result.of_err('err').err() == Option.some('err')
assert Result.of_ok(0).err() == Option.none()

expect(msg) abstractmethod

Returns the contained Ok value.

Because this function may raise an exception, its use is generally discouraged. Instead, prefer to call unwrap_or or unwrap_or_else.

Recommended Message Style We recommend that expect messages are used to describe the reason you expect the Result should be Ok.
Hint:If you’re having trouble remembering how to phrase expect error messages remember to focus on the word “should” as in “env variable should be set by blah” or “the given binary should be available and executable by the current user”.

Parameters:

Name Type Description Default
msg str

The message of the exception.

required

Raises:

Type Description
UnwrapException

Raises if the value is an Err with a message including the passed message and the Err.

Examples:

1
2
3
4
5
assert Result.of_ok(2).expect('error') == 2
try:
    Result.of_err('err').expect('error')
except UnwrapException as e:
    assert str(e) == "ResultError: error: 'err'"

expect_err(msg) abstractmethod

Returns the contained Err value.

Parameters:

Name Type Description Default
msg str

The message of the exception.

required

Raises:

Type Description
UnwrapException

Raises if the value is an Ok with a message including the passed message and the Ok.

Examples:

1
2
3
4
5
assert Result.of_err('err').expect_err('ok') == 'err'
try:
    Result.of_ok(2).expect_err('ok')
except UnwrapException as e:
    assert str(e) == "ResultError: ok: 2"

flatten()

Converts from Result<Result<T, E>, E> to Result<T, E>.

Examples:

1
2
3
assert Result.of_ok('hello') == Result.of_ok(Result.of_ok('hello')).flatten()
assert Result.of_err(6) == Result.of_ok(Result.of_err(6)).flatten()
assert Result.of_err(5) == Result.of_err(5).flatten()
Flattening only removes one level of nesting at a time:
1
2
3
x = Result.of_ok(Result.of_ok(Result.of_ok('hello')))
assert Result.of_ok(Result.of_ok('hello')) == x.flatten()
assert Result.of_ok('hello') == x.flatten().flatten()

inspect(func) abstractmethod

Calls the provided closure with a reference to the contained value (if Ok).

Parameters:

Name Type Description Default
func Callable[[KT], None]

The closure to be executed.

required

Examples:

1
2
3
4
5
k = []
Result.of_ok(2).inspect(lambda x: k.append(x))
assert k == [2]
Result.of_err('err').inspect(lambda x: k.append(x))
assert k == [2]

inspect_err(func) abstractmethod

Calls the provided closure with a reference to the contained value (if Err).

Parameters:

Name Type Description Default
func Callable[[KE], None]

The closure to be executed.

required

Examples:

1
2
3
4
5
k = []
Result.of_ok(2).inspect_err(lambda x: k.append(x))
assert k == []
Result.of_err(-1).inspect_err(lambda x: k.append(x))
assert k == [-1]

is_err() abstractmethod

Returns True if the result is Err.

Examples:

assert not Result.of_ok(2).is_err()
assert Result.of_err('err').is_err()

is_err_and(func) abstractmethod

Returns True if the result is Err.

Parameters:

Name Type Description Default
func Callable[[KE], bool]

The predicate function.

required

Examples:

1
2
3
assert not Result.of_ok(2).is_err_and(lambda x: len(x) == 3)
assert Result.of_err('err').is_err_and(lambda x: len(x) == 3)
assert not Result.of_err('error').is_err_and(lambda x: len(x) == 3)

is_ok() abstractmethod

Returns True if the result is Ok.

Examples:

assert Result.of_ok(2).is_ok()
assert not Result.of_err('err').is_ok()

is_ok_and(func) abstractmethod

Returns True if the result is Ok and the value inside it matches a predicate.

Parameters:

Name Type Description Default
func Callable[[KT], bool]

The predicate function.

required

Examples:

1
2
3
assert Result.of_ok(2).is_ok_and(lambda x: x > 1)
assert not Result.of_ok(0).is_ok_and(lambda x: x > 1)
assert not Result.of_err('error').is_ok_and(lambda x: x > 1)

map(func) abstractmethod

Maps a Result<KT, KE> to Result<U, KE> 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.

Examples:

assert Result.of_ok(2).map(lambda x: x * 2) == Result.of_ok(4)
assert Result.of_err('err').map(lambda x: x * 2) == Result.of_err('err')

map_err(func) abstractmethod

Maps a Result<KT, KE> to Result<KT, F> by applying a function to a contained Err value, leaving the Ok value untouched.

Parameters:

Name Type Description Default
func Callable[[KE], F]

The function to apply to the Err value.

required

Examples:

assert Result.of_ok(2).map_err(lambda x: str(x)) == Result.of_ok(2)
assert Result.of_err(-1).map_err(lambda x: str(x)) == Result.of_err('-1')

map_err_mut(func) abstractmethod

Maps a Result<KT, KE>'s err value by changing it within the closure.

This method require a function to return nothing, and passes a reference into it. Actually, python doesn't differentiate mutable / immutable value, and this method is just for explicit notification.

Parameters:

Name Type Description Default
func Callable[[KE], None]

A callable object that accepts the wrapped value.

required

Examples:

class Test:
    value: int
    def __init__(self, val: int):
        self.value = val

    def change_value(self, new_value: int):
        print('old:', self.value, 'new:', new_value)
        self.value = new_value

maybe_ok = Result.of_err(Test(1))
assert maybe_ok.unwrap_err().value == 1
maybe_ok.map_err_mut(lambda x: x.change_value(5))
assert maybe_ok.unwrap_err().value == 5

map_mut(func) abstractmethod

Maps a Result<KT, KE>'s ok value by changing it within the closure.

This method require a function to return nothing, and passes a reference into it. Actually, python doesn't differentiate mutable / immutable value, and this method is just for explicit notification.

Parameters:

Name Type Description Default
func Callable[[KT], None]

A callable object that accepts the wrapped value.

required

Examples:

class Test:
    value: int
    def __init__(self, val: int):
        self.value = val

    def change_value(self, new_value: int):
        print('old:', self.value, 'new:', new_value)
        self.value = new_value

maybe_ok = Result.of_ok(Test(1))
assert maybe_ok.unwrap().value == 1
maybe_ok.map_mut(lambda x: x.change_value(5))
assert maybe_ok.unwrap().value == 5

map_or(default, func) abstractmethod

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:

Name Type Description Default
default U

The default value.

required
func Callable[[KT], U]

The function to apply to the result.

required

Examples:

assert Result.of_ok('foo').map_or(42, lambda s: len(s)) == 3
assert Result.of_err('bar').map_or(42, lambda s: len(s)) == 42

map_or_else(default, func) abstractmethod

Maps a Result<KT, KE> to U by applying fallback function default to a contained Err value, or function func to a contained Ok value.

This function can be used to unpack a successful result while handling an error.

Parameters:

Name Type Description Default
default Callable[[KE], U]

The fallback function to produce a default value.

required
func Callable[[KT], U]

The function to apply to the success value.

required

Examples:

assert Result.of_ok('foo').map_or_else(lambda e: len(e) + 3, lambda v: len(v)) == 3
assert Result.of_err('bar').map_or_else(lambda e: len(e) + 3, lambda v: len(v)) == 6

of_err(value) staticmethod

Create an Err value.

of_ok(value) staticmethod

Create an Ok value.

ok() abstractmethod

Converts from Result<KT, KE> to Option<KT>.

Converts self into an Option<KT>, and discarding the error, if any.

Examples:

assert Result.of_ok(2).ok() == Option.some(2)
assert Result.of_err('err').ok() == Option.none()

or_else(op) abstractmethod

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:

Name Type Description Default
op Callable[[KE], Result[KT, F]]

The function to be executed.

required

Examples:

def sq(x: int) -> Result[int, int]:
    return Result.of_ok(x * x)

def err(x: int) -> Result[int, int]:
    return Result.of_err(x)

assert Result.of_ok(2).or_else(sq).or_else(sq) == Result.of_ok(2)
assert Result.of_ok(2).or_else(err).or_else(sq) == Result.of_ok(2)
assert Result.of_err(3).or_else(sq).or_else(err) == Result.of_ok(9)
assert Result.of_err(3).or_else(err).or_else(err) == Result.of_err(3)

to_array() abstractmethod

Returns an array containing the possibly contained value.

Examples:

assert Result.of_ok(2).to_array() == [2]
assert Result.of_err('err').to_array() == []

to_either() abstractmethod

Converts the Result to an Either.

The Ok value will be mapped to Either::Left, and the Err value will be mapped to Either::Right.

Examples:

assert Ok(1).to_either() == Left(1)
assert Err(2).to_either() == Right(2)

to_iter()

Alias iter(self.to_array()).

to_pattern() abstractmethod

Returns a flag and the contained value for pattern-matching.

For flags, see Result.OK and Result.ERR.

Returns:

Type Description
Tuple[bool, Union[KT, KE]]

A tuple, where the first element is the flag, and the second element is the value.

Examples:

Built-in pattern-matching is only available in Python 3.10+.

1
2
3
4
5
match Ok("ok").to_pattern:
    case (Result.OK, val):
        print("OK: ", val)      # expect this
    case (Result.ERR, val):
        print("ERR: ", val)

transpose()

Transposes a Result of an Option into an Option of a Result.

Ok(None) will be mapped to None. Ok(Some(_)) and Err(_) will be mapped to Some(Ok(_)) and Some(Err(_)).

Examples:

1
2
3
x = Result.of_ok(Option.some(5))
y = Option.some(Result.of_ok(5))
assert x.transpose() == y

unwrap() abstractmethod

Returns the contained Ok value.

Because this function may raise an exception, its use is generally discouraged. Instead, prefer to call unwrap_or or unwrap_or_else.

Raises:

Type Description
UnwrapException

Raises if the value is an Err, with a panic message provided by the Err’s value.

Examples:

1
2
3
4
5
assert Result.of_ok(2).unwrap() == 2
try:
    Result.of_err('err').unwrap()
except UnwrapException as e:
    assert str(e) == "ResultError: call `Result.unwrap` on an `Err` value: 'err'"

unwrap_err() abstractmethod

Returns the contained Err value.

Raises:

Type Description
UnwrapException

Raises if the value is an Ok, with a panic message provided by the Ok’s value.

Examples:

1
2
3
4
5
assert Result.of_err('err').unwrap_err() == 'err'
try:
    Result.of_ok(2).unwrap_err()
except UnwrapException as e:
    assert str(e) == "ResultError: call `Result.unwrap_err` on an `Ok` value: 2"

unwrap_or(default) abstractmethod

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:

Name Type Description Default
default KT

The default value.

required

Examples:

assert Result.of_ok(9).unwrap_or(2) == 9
assert Result.of_err('err').unwrap_or(2) == 2

unwrap_or_else(op) abstractmethod

Returns the contained Ok value or computes it from a closure.

Parameters:

Name Type Description Default
op Callable[[KE], KT]

The closure to compute.

required

Examples:

assert Result.of_ok(2).unwrap_or_else(lambda s: len(s)) == 2
assert Result.of_err('foo').unwrap_or_else(lambda s: len(s)) == 3

unwrap_unchecked() abstractmethod

Returns the contained value, no matter what it is.

Examples:

assert Ok("foo").unwrap_unchecked() == Err("foo").unwrap_unchecked()