Skip to content

Commit

Permalink
Add validation to BoundResult
Browse files Browse the repository at this point in the history
  • Loading branch information
ilotoki0804 committed Aug 31, 2024
1 parent a103590 commit a054bc5
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
17 changes: 9 additions & 8 deletions src/fieldenum/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,15 @@ def bound(self) -> type[E]: ...
def __bool__(self) -> bool:
return isinstance(self, BoundResult.Success)

def __post_init__(self):
if not issubclass(self.bound, BaseException):
raise IncompatibleBoundError(f"{self.bound} is not an exception.")

if isinstance(self, Failed) and not isinstance(self.error, self.bound):
raise IncompatibleBoundError(
f"Bound {self.bound.__qualname__!r} is not compatible with existing error: {type(self.error).__qualname__}."
)

@overload
def unwrap(self) -> R: ...

Expand Down Expand Up @@ -241,10 +250,6 @@ def rebound[NewBound: BaseException](self, bound: type[NewBound], /) -> BoundRes
return BoundResult.Success(value, bound)

case BoundResult.Failed(error, _):
if not isinstance(error, bound):
raise IncompatibleBoundError(
f"New bound {bound.__qualname__!r} is incompatible with existing error: {type(error).__qualname__}."
)
return BoundResult.Failed(error, bound)

case other:
Expand Down Expand Up @@ -275,10 +280,6 @@ def map[NewReturn](self, func: Callable[[R], BoundResult[NewReturn, Any] | NewRe
return BoundResult.Success(ok, bound)

case BoundResult.Failed(error, _):
if not isinstance(error, bound):
raise IncompatibleBoundError(
f"Bound {bound.__qualname__!r} is not compatible with existing error: {type(error).__qualname__}."
)
return BoundResult.Failed(error, bound)

case other:
Expand Down
2 changes: 1 addition & 1 deletion tests/test_enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def test_bound_result():
BoundResult.Failed(ValueError("error"), ValueError).unwrap()
assert BoundResult.Failed(Exception("err"), Exception).unwrap(34556) == 34556
assert BoundResult.Success(False, Exception)
assert not BoundResult.Failed(True, Exception)
assert not BoundResult.Failed(Exception("Some exception."), Exception)

assert BoundResult.Success(2342, Exception).map_as_is(str) == BoundResult.Success("2342", Exception)
error = ValueError(123)
Expand Down

0 comments on commit a054bc5

Please sign in to comment.