Functional composition#

When composing predicates for phantom types it won’t take long before you reach after functional composition. Unfortunately, fully supporting a typed n-ary compose functions isn’t yet feasible without shipping a custom mypy plugin. In lieu of having that effort in place, a simpler but fully typed compose2 function is shipped. The door, however, is left wide open for the possibility of shipping an n-ary, generalized compose function in the future.

phantom.fn.compose2(a, b)[source]#

Returns a function composed from the two given functions a and b such that calling compose2(a, b)(x) is equivalent to calling a(b(x)).

>>> compose2("".join, reversed)("!olleH")
'Hello!'
Parameters:
  • a (typing.Callable[[typing.TypeVar(AA)], typing.TypeVar(AR)]) –

  • b (typing.Callable[[typing.TypeVar(BA)], typing.TypeVar(AA)]) –

Return type:

typing.Callable[[typing.TypeVar(BA)], typing.TypeVar(AR)]

phantom.fn.excepts(exception, negate=False)[source]#

Turn a unary function that raises an exception into a boolean predicate.

>>> def validate_positive(number: int) -> None:
...     if number < 0: raise ValueError
>>> is_positive = excepts(ValueError)(validate_positive)
>>> is_positive(0), is_positive(-1)
(True, False)