[Python] TypeVarTuple Unpack all contained types and use them as type arguments

Discussão em 'Python' iniciado por Stack, Fevereiro 15, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página