[Python] Is it possible to type a list of tuples of identical generic types, with a static...

Discussão em 'Python' iniciado por Stack, Julho 7, 2025.

  1. Stack

    Stack Membro Participativo

    Consider the following:

    from typing import TypeVar, Generic

    class A(): pass
    class B(A): pass
    class C(A): pass


    T = TypeVar("T", bound=A)


    class Container(Generic[T]):
    def __init__(x: T):
    pass

    b: Container = Container(B())
    c: Container[C] = Container(C())


    How do I type-hint a function foo that will accept any list of tuples of identically typed containers:

    foo([
    (b, b),
    (c, c)
    ])


    but refuse this (heterogeneous tuple):

    foo([
    (c, b), # tuples elements are not the same type
    (c, c)
    ])


    I tried this:

    ListOfSameContainerTuples = list[tuple[Container[T], Container[T]]]

    def foo(containers: ListOfSameContainerTuples[T]):
    pass


    but it doesn't work:

    foo([
    (b, b),
    (c, c)
    ])
    # error: Argument 1 to "foo" has incompatible type "list[tuple[object, object]]";
    # expected "list[tuple[Container[<nothing>], Container[<nothing>]]]" [arg-type]

    foo([
    (c, b),
    (c, c)
    ])
    # error: List item 0 has incompatible type "tuple[Container[C], Container]"; expected "tuple[Container[C], Container[C]]" [list-item]


    The second error on mypy looks good, but I don't understand the first one:

    • Why does mypy not know the type of b and c ?
    • Why is my type signature Container[<nothing>] ?

    I tried solutions from Tuple with multiple numbers of arbitrary but equal type, to no avail.

    Continue reading...

Compartilhe esta Página