[Python] Why are type-checkers fine with covariant method parameters when they are in a union?

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

  1. Stack

    Stack Membro Participativo

    Method parameters should be contravariant, hence defining a covariant generic should raise a type error. However when using a covariant generic in a union pyright, mypy and pyre-check all do not report an error on the following code:

    from typing import TypeVar, Generic, TypeAlias, Any

    T_co = TypeVar("T_co", covariant=True)

    class Foo(Generic[T_co]):

    def a(self, arg: T_co) -> Any: # Error, like expected as T_co is covariant.
    ...

    def b(self, arg: int | T_co) -> Any: # No error, expected one
    ...


    As all these type-checkers do not raise an error I wonder is this actually fine, shouldn't this also break type-safety? If it is fine can you explain to why, what differs from a pure covariant implementation that is definitely not safe, shouldn't I be able to break it as well? Or if its not safe, is there an explanation why all type-checkers have the same gap here?

    Continue reading...

Compartilhe esta Página