Skip to content

Commit

Permalink
feat: add overload to unwrap_or_raise to raise the exception itself
Browse files Browse the repository at this point in the history
  • Loading branch information
mokeyish committed Jul 23, 2024
1 parent f4d5c07 commit 596c871
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/result/result.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@
Iterator,
Literal,
NoReturn,
Optional,
Type,
TypeVar,
Union,
overload,
)

if sys.version_info >= (3, 10):
Expand Down Expand Up @@ -350,11 +352,22 @@ def unwrap_or_else(self, op: Callable[[E], T]) -> T:
"""
return op(self._value)


@overload
def unwrap_or_raise(self) -> NoReturn:
...
@overload
def unwrap_or_raise(self, e: Type[TBE]) -> NoReturn:
...
def unwrap_or_raise(self, e: Optional[Type[TBE]] = None) -> NoReturn:
"""
The contained result is ``Err``, so raise the exception with the value.
"""
raise e(self._value)
if e is not None:
raise e(self._value)
if isinstance(self._value, BaseException):
raise self._value
self.unwrap()

def map(self, op: object) -> Err[E]:
"""
Expand Down
4 changes: 4 additions & 0 deletions tests/test_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,10 @@ def test_unwrap_or_raise() -> None:
n.unwrap_or_raise(ValueError)
assert exc_info.value.args == ('nay',)

n2 = Err(ValueError('nay'))
with pytest.raises(ValueError) as exc_info:
n2.unwrap_or_raise()


def test_map() -> None:
o = Ok('yay')
Expand Down

0 comments on commit 596c871

Please sign in to comment.