Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Result or_else methods #226

Merged
merged 1 commit into from
Aug 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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")
Loading