Reputation: 1526
I would like to use a generic class in Python that is instantiated with a variable number of type parameters. This can be achieved using TypeVarTuple
. For each of these type parameters, I want to fill a data structure (e.g., a list
). The list can have a different length for each data type. Ideally, I would like to type hint a tuple of lists, each corresponding to a type from the TypeVarTuple.
Here is a very simplified example of what I would like to achieve (note that the syntax below does not work):
from typing import Generic, Tuple, List
from typing_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple('Ts')
class Test(Generic[Unpack[Ts]]):
def __init__(self) -> None:
self.content: Unpack[Tuple[List[Ts]]] = []
def call(self, *values: Unpack[List[Ts]]):
for v, c in zip(values, self.content):
c.extend(v) # noqa
class Implementation(Test[int, str, int]):
pass
i = Implementation()
i.call([1, 2, 3], [], [2])
Is something like this possible with Python's type hinting? If so, how can it be properly implemented?
Upvotes: 0
Views: 379
Reputation: 997
Use *
-unpacking, so like class Test(Generic[*Ts]): ...
Since Ts
is a TypeVarTuple
, using *Ts
is valid in this context and also exactly what you were looking for.
Upvotes: 0