Annotate Callable input params from a generic tuple #1462
-
Hi, I am trying to annotate a rather simple PyTorch Dataset wrapper for data transformations. The snippet below should be the best explanation of what I want to achieve. Right now I get:
from mypy which works as expected. How do I solve this and indicate that the from typing import Sequence, Callable, TypeVar, Generic
from torch.utils.data import Dataset, IterableDataset, TensorDataset
class StrDs(Dataset[tuple[str, str]]):
def __init__(self):
self.d = [("1", "10"), ("2", "20"), ("3", "30")]
def __getitem__(self, idx: int) -> tuple[str, str]:
return self.d[idx]
InT = TypeVar("InT", bound=tuple)
OutT = TypeVar("OutT", bound=tuple)
class TransformableDatasetWrapper(Generic[InT, OutT], Dataset[InT]):
def __init__(
self, d: Dataset[InT], t: Callable[[*InT], OutT] # <-- * is pseudocode to show my intentions
):
self.d = d
self.t = t
def get(self, i: int) -> OutT:
return self.t(*self.d[i])
def str_to_int(i: str, ii: str) -> tuple[int, int]:
return int(i), int(ii)
TransformableDatasetWrapper[tuple[str, str], tuple[int, int]](StrDs(), str_to_int) Thanks for any help. I have found some fairly similar questions to this one, but still couldn't solve it. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
You are looking for https://peps.python.org/pep-0646/ which is not fully supported yet :) |
Beta Was this translation helpful? Give feedback.
Internal error always means bug in mypy and you can open an issue there.
There are multiple type checkers available. Pyright and pyre both have support for typevartuple and you can test your code with them.
Your code does have a few errors, but is close. Here's a fixed version that type checks with pyright,