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 25, 2024
1 parent f4d5c07 commit e57b7f3
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
23 changes: 21 additions & 2 deletions 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 @@ -138,7 +140,13 @@ def unwrap_or_else(self, op: object) -> T:
"""
return self._value

def unwrap_or_raise(self, e: object) -> T:
@overload
def unwrap_or_raise(self) -> T:
...
@overload
def unwrap_or_raise(self, e: Type[TBE]) -> T:
...
def unwrap_or_raise(self, e: Optional[Type[TBE]] = None) -> T:
"""
Return the value.
"""
Expand Down Expand Up @@ -350,11 +358,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 e57b7f3

Please sign in to comment.