Skip to content
Merged
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
56 changes: 34 additions & 22 deletions expression/extra/result/catch.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,42 +2,54 @@

from collections.abc import Callable
from functools import wraps
from typing import Any, cast, overload
from typing import Any, Never, ParamSpec, Protocol, cast, overload

from typing_extensions import TypeVar

from expression.core import Error, Ok, Result


# Use typing_extensions.TypeVar because type parameter defaults require Python 3.13 syntax.
# Keep Python 3.12 support while defaulting to Never so plain returns do not infer an Unknown error channel.
_TSource = TypeVar("_TSource")
_TExisting = TypeVar("_TExisting", default=Never)
_TError = TypeVar("_TError", bound=Exception, covariant=True, default=Exception)
_P = ParamSpec("_P")


class _Catch(Protocol[_TError]):
def __call__(
self, fn: Callable[_P, _TSource | Result[_TSource, _TExisting]]
) -> Callable[_P, Result[_TSource, _TExisting | _TError]]: ...


@overload
def catch[TError_: Exception, TSource, TError: Exception](
exception: type[TError_],
) -> Callable[
[Callable[..., TSource | Result[TSource, TError]]],
Callable[..., Result[TSource, TError | TError_]],
]: ...
def catch[TError: Exception](*, exception: type[TError]) -> _Catch[TError]: ...


@overload
def catch[TSource, TError: Exception](
f: Callable[..., TSource], *, exception: type[TError]
) -> Callable[..., Result[TSource, TError]]: ...


def catch[TSource, TError: Exception]( # type: ignore
f: Callable[..., TSource] | None = None, *, exception: type[TError]
) -> Callable[
[Callable[..., TSource]],
Callable[..., Result[TSource, TError]] | Result[TSource, TError],
]:
def decorator(fn: Callable[..., TSource]) -> Callable[..., Result[TSource, TError]]:
def catch(
f: Callable[_P, _TSource | Result[_TSource, _TExisting]], *, exception: type[_TError]
) -> Callable[_P, Result[_TSource, _TExisting | _TError]]: ...


def catch[TError: Exception](
f: Callable[..., Any] | None = None, *, exception: type[TError]
) -> _Catch[TError] | Callable[..., Result[Any, Any]]:
"""Catch the selected exception, preserving arguments and existing Result values."""

def decorator(
fn: Callable[_P, _TSource | Result[_TSource, _TExisting]],
) -> Callable[_P, Result[_TSource, _TExisting | TError]]:
@wraps(fn)
def wrapper(*args: Any, **kwargs: Any) -> Result[TSource, TError]:
def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> Result[_TSource, _TExisting | TError]:
try:
out = fn(*args, **kwargs)
except exception as exn:
return Error(cast(TError, exn))
return Error(exn)
else:
if isinstance(out, (Ok, Error)):
return cast(Result[TSource, TError], out)
return cast(Result[_TSource, _TExisting], out)

return Ok(out)

Expand Down
66 changes: 65 additions & 1 deletion tests/test_catch.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from collections.abc import Generator
from typing import Any
from typing import Any, assert_type

import pytest

Expand Down Expand Up @@ -105,3 +105,67 @@ def fn(a: int) -> Generator[str, str, str]:
assert isinstance(ex, TypeError)
case _:
assert False


def test_catch_preserves_signature_and_plain_return_type():
def add(a: int, *, b: int = 1) -> int:
return a + b

wrapped = catch(add, exception=ValueError)
decorated = catch(exception=ValueError)(add)
assert_type(wrapped(3, b=4), Result[int, ValueError])
assert_type(decorated(3, b=4), Result[int, ValueError])
assert wrapped(3, b=4) == decorated(3, b=4) == Ok(7)
assert wrapped.__name__ == "add"


def test_catch_preserves_existing_result_and_error_type():
original: Result[int, str] = Error("failure")

def fn(value: int) -> Result[int, str]:
return Ok(value) if value else original

wrapped = catch(fn, exception=ValueError)
decorated = catch(exception=ValueError)(fn)
assert_type(wrapped(1), Result[int, str | ValueError])
assert_type(decorated(1), Result[int, str | ValueError])
assert wrapped(1) == decorated(1) == Ok(1)
assert wrapped(0) is original
assert decorated(0) is original


def test_catch_chained_preserves_types():
@catch(exception=KeyError)
@catch(exception=ValueError)
def fn(value: int) -> int:
return value

assert_type(fn(1), Result[int, ValueError | KeyError])
assert fn(1) == Ok(1)


def test_catch_direct_call_catches_exception():
error = ValueError("failure")

def fn() -> int:
raise error

wrapped = catch(fn, exception=ValueError)
assert wrapped() == Error(error)


def test_catch_decorator_can_wrap_different_signatures():
decorator = catch(exception=ValueError)

@decorator
def number(value: int) -> int:
return value

@decorator
def text(*, value: str) -> str:
return value

assert_type(number(1), Result[int, ValueError])
assert_type(text(value="hello"), Result[str, ValueError])
assert number(1) == Ok(1)
assert text(value="hello") == Ok("hello")
17 changes: 17 additions & 0 deletions typing_tests/negative.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from expression import Error, MailboxProcessor, Nothing, Option, Result, Some, TaggedUnion, apipe, case, tag
from expression.collections import Block, Map, TypedArray
from expression.extra import async_result
from expression.extra.result import catch


def unchecked(value: Option[int]) -> None:
Expand Down Expand Up @@ -144,3 +145,19 @@ async def integer_error(value: int) -> Result[str, int]:

StringErrorBind = Callable[[Result[int, str]], Awaitable[Result[str, str]]]
wrong_async_bind: StringErrorBind = async_result.bind(integer_error) # type-error


# Exception-catching decorators retain positional and keyword parameter types.


def catch_source(value: int, *, suffix: str) -> str:
return f"{value}{suffix}"


caught_direct = catch(catch_source, exception=ValueError)
caught_decorated = catch(exception=ValueError)(catch_source)
caught_direct("wrong", suffix="!") # type-error
caught_decorated(1, suffix=2) # type-error
caught_direct(1, "!") # type-error
caught_decorated(1) # type-error
catch(ValueError) # type-error
Loading