Skip to content

Commit efb2de9

Browse files
Added Result or_else methods (#226)
1 parent 7a92a9d commit efb2de9

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

expression/core/result.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,14 @@ def swap(self) -> Result[_TError, _TSource]:
180180
case Result(error=error):
181181
return Result(ok=error)
182182

183+
def or_else(self, other: Result[_TSource, _TError]) -> Result[_TSource, _TError]:
184+
"""Return the result if it is Ok, otherwise return the other result."""
185+
return self if self.is_ok() else other
186+
187+
def or_else_with(self, other: Callable[[_TError], Result[_TSource, _TError]]) -> Result[_TSource, _TError]:
188+
"""Return the result if it is Ok, otherwise return the result of the other function."""
189+
return self if self.is_ok() else other(self.error)
190+
183191
def to_option(self) -> Option[_TSource]:
184192
"""Convert result to an option."""
185193
match self:

tests/test_result.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -523,3 +523,50 @@ def test_result_swap_with_error():
523523
error: Result[str, int] = Error(1)
524524
xs = result.swap(error)
525525
assert xs == Ok(1)
526+
527+
def test_ok_or_else_ok():
528+
xs: Result[int, str] = Ok(42)
529+
ys = xs.or_else(Ok(0))
530+
assert ys == Ok(42)
531+
532+
533+
def test_ok_or_else_error():
534+
xs: Result[int, str] = Ok(42)
535+
ys = xs.or_else(Error("new error"))
536+
assert ys == Ok(42)
537+
538+
539+
def test_error_or_else_ok():
540+
xs: Result[int, str] = Error("original error")
541+
ys = xs.or_else(Ok(0))
542+
assert ys == Ok(0)
543+
544+
545+
def test_error_or_else_error():
546+
xs: Result[int, str] = Error("original error")
547+
ys = xs.or_else(Error("new error"))
548+
assert ys == Error("new error")
549+
550+
551+
def test_ok_or_else_with_ok():
552+
xs: Result[str, str] = Ok("good")
553+
ys = xs.or_else_with(lambda error: Ok(f"new error from {error}"))
554+
assert ys == Ok("good")
555+
556+
557+
def test_ok_or_else_with_error():
558+
xs: Result[str, str] = Ok("good")
559+
ys = xs.or_else_with(lambda error: Ok(f"new error from {error}"))
560+
assert ys == Ok("good")
561+
562+
563+
def test_error_or_else_with_ok():
564+
xs: Result[str, str] = Error("original error")
565+
ys = xs.or_else_with(lambda error: Ok(f"fixed {error}"))
566+
assert ys == Ok("fixed original error")
567+
568+
569+
def test_error_or_else_with_error():
570+
xs: Result[str, str] = Error("original error")
571+
ys = xs.or_else_with(lambda error: Error(f"new error from {error}"))
572+
assert ys == Error("new error from original error")

0 commit comments

Comments
 (0)