Skip to content

Commit

Permalink
Added Result or_else methods (#226)
Browse files Browse the repository at this point in the history
  • Loading branch information
brendanmaguire authored Aug 28, 2024
1 parent 7a92a9d commit efb2de9
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
8 changes: 8 additions & 0 deletions expression/core/result.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,14 @@ def swap(self) -> Result[_TError, _TSource]:
case Result(error=error):
return Result(ok=error)

def or_else(self, other: Result[_TSource, _TError]) -> Result[_TSource, _TError]:
"""Return the result if it is Ok, otherwise return the other result."""
return self if self.is_ok() else other

def or_else_with(self, other: Callable[[_TError], Result[_TSource, _TError]]) -> Result[_TSource, _TError]:
"""Return the result if it is Ok, otherwise return the result of the other function."""
return self if self.is_ok() else other(self.error)

def to_option(self) -> Option[_TSource]:
"""Convert result to an option."""
match self:
Expand Down
47 changes: 47 additions & 0 deletions tests/test_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -523,3 +523,50 @@ def test_result_swap_with_error():
error: Result[str, int] = Error(1)
xs = result.swap(error)
assert xs == Ok(1)

def test_ok_or_else_ok():
xs: Result[int, str] = Ok(42)
ys = xs.or_else(Ok(0))
assert ys == Ok(42)


def test_ok_or_else_error():
xs: Result[int, str] = Ok(42)
ys = xs.or_else(Error("new error"))
assert ys == Ok(42)


def test_error_or_else_ok():
xs: Result[int, str] = Error("original error")
ys = xs.or_else(Ok(0))
assert ys == Ok(0)


def test_error_or_else_error():
xs: Result[int, str] = Error("original error")
ys = xs.or_else(Error("new error"))
assert ys == Error("new error")


def test_ok_or_else_with_ok():
xs: Result[str, str] = Ok("good")
ys = xs.or_else_with(lambda error: Ok(f"new error from {error}"))
assert ys == Ok("good")


def test_ok_or_else_with_error():
xs: Result[str, str] = Ok("good")
ys = xs.or_else_with(lambda error: Ok(f"new error from {error}"))
assert ys == Ok("good")


def test_error_or_else_with_ok():
xs: Result[str, str] = Error("original error")
ys = xs.or_else_with(lambda error: Ok(f"fixed {error}"))
assert ys == Ok("fixed original error")


def test_error_or_else_with_error():
xs: Result[str, str] = Error("original error")
ys = xs.or_else_with(lambda error: Error(f"new error from {error}"))
assert ys == Error("new error from original error")

0 comments on commit efb2de9

Please sign in to comment.