1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Type invariance in generic class when callable is involved

Discussão em 'Python' iniciado por Stack, Setembro 13, 2025.

  1. Stack

    Stack Membro Participativo

    Why, in the following example, the type variable T in class E is invariant?

    class C:
    pass

    class D(C):
    pass

    class E[T: C = C]:
    def g(self, f: Callable[[], T]) -> T:
    return f()

    x: E = E[D]() # error


    Callable return types are covariant. This typechecks:

    x = E() # x is E[C]
    x.g(D) # f is Callable[[], D] which fits on Callable[[], C]


    Removing or otherwise changing the callable to not have T as a return type makes T covariant again:

    class E[T: C = C]:
    def g(self, f: Callable[[], None]) -> T:
    return cast(T, f()) # anything

    x: E = E[D]() # OK


    Hence, considering the first example, what is the rationale for E[D] not be compatible with E[C]?

    Continue reading...

Compartilhe esta Página