Annotations for variable length function composition/pipeline. #1766
Unanswered
randolf-scholz
asked this question in
Q&A
Replies: 1 comment 1 reply
-
Right now that is not possible. However, you can chain method calls to achieve the same result: from typing import Generic, TypeVar
from collections.abc import Callable
A = TypeVar("A")
B = TypeVar("B")
C = TypeVar("C")
class Pipe(Generic[A, B]):
def __init__(self, fn: Callable[[A], B]) -> None:
self._fn = fn
def __call__(self, arg: A, /) -> B:
return self._fn(arg)
def then(self, fn: Callable[[B], C], /) -> "Pipe[A, C]":
return Pipe(lambda a: fn(self._fn(a))) Then you can do |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Is there any simple way to have more precise type hints for
Pipeline
, without going completely overboard with overloads?In particular, it would be nice to have:
Pipeline(Transform[X_first, Y_last])
Pipeline([])
andPipeline([Transform[X,Y]])
.The best I could come up with handles (1) and (3), but requires changing the
__init__
-signature from(self, funcs: Iterable[Transform], /)
toself, *funcs: *tuple[Transform, ...], /)
, and the introduction of an additional subclassIdentityPipe
.I wonder if there is any simpler/better way of doing it.
Code sample in pyright playground
Beta Was this translation helpful? Give feedback.
All reactions