It'd be nice if Sequential had the same type parameter structure as Linear, which we've been assuming will be generic in just the input and output types: class Linear(Generic[In, Out]): def __call__(x: Tensor[Batch, In]) -> Tensor[Batch, Out]: ... That would suggest: class Sequential(Generic[A, C]): def __init__(self, f1: Callable[[A], B], f2: Callable[[B], C]): pass I think the reason we thought this wouldn't work when discussing it in the tensor typing meeting was that it would rely on a type variable B that wasn't one of the type parameters to the class - but surprisingly, it seems to be fine in mypy: https://mypy-play.net/?mypy=latest&python=3.10&gist=e4b1d2d7b70d79f62eadeca3d711193d On Mon, 16 Aug 2021 at 19:13, Alfonso L. Castaño <alfonsoluis.castanom@um.es> wrote:
Hi,
Context: during the typing meeting of this week Brandon presented the idea of introducing a Compose type operator, which takes a variadic of callables, checks that they compose, and returns the type of the composed function.
To follow-up on the discussion about Compose:
We were wondering what can be achieved nowadays without custom operators, just relying on overload. Let's think about the example of a compose function, we could do the following right?
from typing import Callable as Call
# Overloads def compose(f1: Call[A,B]) -> Call[A,B] def compose(f1: Call[A,B], f2: Call[B,C]) -> Call[A,C] def compose(f1: Call[A,B], f2: Call[B,C], f3: Call[C,D]) -> Call[A,D] ...
What is less obvious is how would we type a class like torch.nn.Sequential, which would look like this with the Compose operator:
class Sequential(Generic[A,*Ts]): def __init__(self, fs: *Ts) def __call__(self, in: A) -> Compose[*Ts]
Here we can't overload the class definition, so what can be done? We had a couple of ideas but they would not really work for a variable number of arguments because we can't overload. An example of those approaches would be:
class Sequential(Generic[A,B,C]): def __init__(self, f1: Callable[A,B], f2: Callable[B,C]): ... def __call__(self, in: A) -> C: ....
Best, Alfonso. _______________________________________________ Typing-sig mailing list -- typing-sig@python.org To unsubscribe send an email to typing-sig-leave@python.org https://mail.python.org/mailman3/lists/typing-sig.python.org/ Member address: mrahtz@google.com