[Python] Mypy reports parameter whose type is a TypeVar bound to the same type as its default...

Discussão em 'Python' iniciado por Stack, Março 20, 2025.

  1. Stack

    Stack Membro Participativo

    When annotating a function parameter with a bound TypeVar, giving it a default value results in the parameter having a union type between the TypeVar and the default value type, even though the default value is of the TypeVar type.

    Example:

    class A:
    pass

    class B(A):
    pass

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

    def get_instance(cls: type[Instance] = A) -> Instance:
    return cls()


    Running mypy yields the following error: error: Incompatible default for argument "cls" (default has type "Type[A]", argument has type "Type[Instance]").

    reveal_type is correct in both cases:

    instance_a = get_instance(cls=A)
    reveal_type(instance_a) # note: Revealed type is "A"

    instance_b = get_instance(cls=B)
    reveal_type(instance_b) # note: Revealed type is "B"


    How do I correctly annotate get_instance so that I can keep the default argument?

    Continue reading...

Compartilhe esta Página