Skip to content

Commit

Permalink
chore: deduplicate return_value handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Picalines committed Jun 29, 2024
1 parent 3fac4bf commit 38ff10c
Showing 1 changed file with 19 additions and 11 deletions.
30 changes: 19 additions & 11 deletions utils/result.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,29 +82,38 @@ def do_error(value: UT) -> NoReturn:
@staticmethod
def do(*, error: type[UE] = object) -> "Callable[[Callable[TArgs, UT]], Callable[TArgs, Result[UT, UE]]]":
def decorator(func):
def handle_exception(raised: Exception):
match raised:
case ResultDoError() as do_error:
return Result.error(do_error.value)
case Exception() as unknown_exception:
print('[outer-scout-blender]', unknown_exception)
return Result.error(str(raised))

def wrap_return_value(return_value):
if isinstance(return_value, Result):
return return_value
return Result.ok(return_value)

if isgeneratorfunction(func):

@wraps(func)
def wrapper(*args, **kwargs):
try:
return_value = yield from func(*args, **kwargs)
except ResultDoError as do_error:
return_value = Result.error(do_error.value)
if not isinstance(return_value, Result):
return_value = Result.ok(return_value)
return return_value
except Exception as exception:
return_value = handle_exception(exception)
return wrap_return_value(return_value)

else:

@wraps(func)
def wrapper(*args, **kwargs):
try:
return_value = func(*args, **kwargs)
except ResultDoError as do_error:
return_value = Result.error(do_error.value)
if not isinstance(return_value, Result):
return_value = Result.ok(return_value)
return return_value
except Exception as exception:
return_value = handle_exception(exception)
return wrap_return_value(return_value)

return wrapper

Expand All @@ -124,4 +133,3 @@ def __repr__(self) -> str:
if self.is_ok:
return f"Ok({self.__value!r})"
return f"Error({self.__error!r})"

0 comments on commit 38ff10c

Please sign in to comment.