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
46 changes: 45 additions & 1 deletion docs/reference/pipe.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,48 @@
```{eval-rst}
.. automodule:: expression.core.pipe
:members:
```
```

## Asynchronous pipelines

Use `apipe` to mix synchronous functions and coroutine-returning functions:

```python
from expression import apipe

async def increment(value: int) -> int:
return value + 1

async def example() -> str:
return await apipe(2, increment, lambda value: value * 3, str)
```

`apipe` starts when awaited and executes stages sequentially. It awaits a native
coroutine supplied as the initial value or returned by a stage once. Exceptions
and cancellation propagate, and later stages do not run.

Other values pass through unchanged, including `Option` and `Result`, even though
these types implement `__await__`. Tasks, futures, and custom awaitables also pass
through unchanged: use an `async def` wrapper that explicitly awaits them when
you want their resolved values. The existing `pipe` never inserts awaits.

For asynchronous Result mapping, use `expression.extra.async_result.bind`:

```python
from expression import Ok, Result, apipe
from expression.extra import async_result

async def increment(value: int) -> Result[int, str]:
return Ok(value + 1)

async def example() -> Result[str, str]:
return await apipe(Ok(2), async_result.bind(increment), lambda value: value.map(str))
```

`bind` skips the mapper on `Error`; plain `apipe` itself does not short-circuit
Result values.

```{eval-rst}
.. automodule:: expression.core.apipe
:members:
```
2 changes: 2 additions & 0 deletions expression/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
TailCall,
TailCallResult,
Try,
apipe,
case,
compose,
curry,
Expand Down Expand Up @@ -84,6 +85,7 @@
"TailCallResult",
"Try",
"__version__",
"apipe",
"case",
"collections",
"compose",
Expand Down
2 changes: 2 additions & 0 deletions expression/core/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Core abstractions such as pipes, options and results."""

from . import aiotools, option, result, tagged_union
from .apipe import apipe
from .builder import Builder
from .compose import compose
from .curry import curry, curry_flip, pipeable
Expand Down Expand Up @@ -48,6 +49,7 @@
"TailCallResult",
"Try",
"aiotools",
"apipe",
"case",
"compose",
"curry",
Expand Down
161 changes: 161 additions & 0 deletions expression/core/apipe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
"""Asynchronous pipe composition.

The pipe handles both synchronous and asynchronous functions; if a function
returns a Coroutine, it is awaited before its result is passed to the next function.
"""

import inspect
from collections.abc import Callable, Coroutine
from typing import Any, TypeVar, overload


_A = TypeVar("_A")
_B = TypeVar("_B")
_C = TypeVar("_C")
_D = TypeVar("_D")
_E = TypeVar("_E")
_F = TypeVar("_F")
_G = TypeVar("_G")
_H = TypeVar("_H")
_T = TypeVar("_T")
_J = TypeVar("_J")

_X = TypeVar("_X")
_Y = TypeVar("_Y")

SyncCallable = Callable[[_X], _Y]
AsyncCallable = Callable[[_X], Coroutine[Any, Any, _Y]]
SyncOrAsyncCallable = SyncCallable[_X, _Y] | AsyncCallable[_X, _Y]


@overload
async def apipe(value: Coroutine[Any, Any, _A] | _A, /) -> _A: ...


@overload
async def apipe(
value: Coroutine[Any, Any, _A] | _A,
fn1: SyncOrAsyncCallable[_A, _B],
/,
) -> _B: ...


@overload
async def apipe(
value: Coroutine[Any, Any, _A] | _A,
fn1: SyncOrAsyncCallable[_A, _B],
fn2: SyncOrAsyncCallable[_B, _C],
/,
) -> _C: ...


@overload
async def apipe(
value: Coroutine[Any, Any, _A] | _A,
fn1: SyncOrAsyncCallable[_A, _B],
fn2: SyncOrAsyncCallable[_B, _C],
fn3: SyncOrAsyncCallable[_C, _D],
/,
) -> _D: ...


@overload
async def apipe(
value: Coroutine[Any, Any, _A] | _A,
fn1: SyncOrAsyncCallable[_A, _B],
fn2: SyncOrAsyncCallable[_B, _C],
fn3: SyncOrAsyncCallable[_C, _D],
fn4: SyncOrAsyncCallable[_D, _E],
/,
) -> _E: ...


@overload
async def apipe(
value: Coroutine[Any, Any, _A] | _A,
fn1: SyncOrAsyncCallable[_A, _B],
fn2: SyncOrAsyncCallable[_B, _C],
fn3: SyncOrAsyncCallable[_C, _D],
fn4: SyncOrAsyncCallable[_D, _E],
fn5: SyncOrAsyncCallable[_E, _F],
/,
) -> _F: ...


@overload
async def apipe(
value: Coroutine[Any, Any, _A] | _A,
fn1: SyncOrAsyncCallable[_A, _B],
fn2: SyncOrAsyncCallable[_B, _C],
fn3: SyncOrAsyncCallable[_C, _D],
fn4: SyncOrAsyncCallable[_D, _E],
fn5: SyncOrAsyncCallable[_E, _F],
fn6: SyncOrAsyncCallable[_F, _G],
/,
) -> _G: ...


@overload
async def apipe(
value: Coroutine[Any, Any, _A] | _A,
fn1: SyncOrAsyncCallable[_A, _B],
fn2: SyncOrAsyncCallable[_B, _C],
fn3: SyncOrAsyncCallable[_C, _D],
fn4: SyncOrAsyncCallable[_D, _E],
fn5: SyncOrAsyncCallable[_E, _F],
fn6: SyncOrAsyncCallable[_F, _G],
fn7: SyncOrAsyncCallable[_G, _H],
/,
) -> _H: ...


@overload
async def apipe(
value: Coroutine[Any, Any, _A] | _A,
fn1: SyncOrAsyncCallable[_A, _B],
fn2: SyncOrAsyncCallable[_B, _C],
fn3: SyncOrAsyncCallable[_C, _D],
fn4: SyncOrAsyncCallable[_D, _E],
fn5: SyncOrAsyncCallable[_E, _F],
fn6: SyncOrAsyncCallable[_F, _G],
fn7: SyncOrAsyncCallable[_G, _H],
fn8: SyncOrAsyncCallable[_H, _T],
/,
) -> _T: ...


@overload
async def apipe(
value: Coroutine[Any, Any, _A] | _A,
fn1: SyncOrAsyncCallable[_A, _B],
fn2: SyncOrAsyncCallable[_B, _C],
fn3: SyncOrAsyncCallable[_C, _D],
fn4: SyncOrAsyncCallable[_D, _E],
fn5: SyncOrAsyncCallable[_E, _F],
fn6: SyncOrAsyncCallable[_F, _G],
fn7: SyncOrAsyncCallable[_G, _H],
fn8: SyncOrAsyncCallable[_H, _T],
fn9: SyncOrAsyncCallable[_T, _J],
/,
) -> _J: ...


async def apipe(value: Any, *functions: SyncOrAsyncCallable[Any, Any]) -> Any:
"""Apply mixed synchronous and asynchronous stages sequentially.

Await native coroutines in the initial value and each stage's output once.
Other values, including Option, Result, tasks, and futures, pass through
unchanged. Wrap other awaitables in an async function to resolve them.
Execution starts when the returned coroutine is awaited. Exceptions and
cancellation propagate without running subsequent stages.
"""
if inspect.iscoroutine(value):
value = await value
for function in functions:
value = function(value)
if inspect.iscoroutine(value):
value = await value
return value


__all__ = ["apipe"]
3 changes: 3 additions & 0 deletions expression/core/result.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,9 @@ def __call__(self, source: Ok[_A]) -> _R: ...
@overload
def __call__(self, source: Error[_F]) -> Error[_F]: ...

@overload
def __call__(self, source: Result[_A, _F]) -> _R | Error[_F]: ...

def __call__(self, source: Result[_A, _F]) -> _R | Error[_F]:
return source.bind(self._mapper)

Expand Down
4 changes: 2 additions & 2 deletions expression/extra/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
functions.
"""

from . import option, result
from . import async_result, option, result


__all__ = ["option", "result"]
__all__ = ["async_result", "option", "result"]
6 changes: 6 additions & 0 deletions expression/extra/async_result/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
"""Extra async_result functions."""

from .async_result import bind


__all__ = ["bind"]
24 changes: 24 additions & 0 deletions expression/extra/async_result/async_result.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from collections.abc import Awaitable, Callable, Coroutine
from typing import Any, TypeVar

from expression import Result
from expression.effect.async_result import async_result


_TSource = TypeVar("_TSource")
_TResult = TypeVar("_TResult")
_TError = TypeVar("_TError")


def bind(
mapper: Callable[[_TSource], Awaitable[Result[_TResult, _TError]]],
) -> Callable[[Result[_TSource, _TError]], Coroutine[Any, Any, Result[_TResult, _TError]]]:
"""Apply an asynchronous mapper to Ok, preserving Error without calling it."""

async def wrapped(result: Result[_TSource, _TError]) -> Result[_TResult, _TError]:
return await async_result.bind(result, mapper)

return wrapped


__all__ = ["bind"]
Loading
Loading