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

feat: add overload to unwrap_or_raise to raise the exception itself #192

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
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
Loading