[Python] mypy reporting an error in function with generic type

Discussão em 'Python' iniciado por Stack, Janeiro 27, 2025.

  1. Stack

    Stack Membro Participativo

    Why does mypy report an error in the code below:

    from typing import Self, reveal_type, Protocol


    class A:
    def dup(self) -> list[Self]:
    return [self, self]


    class B:
    def dup(self) -> list[Self]:
    return [self, self]


    class C:
    def dup(self) -> list[Self]:
    return [self, self]


    class HasDup(Protocol):
    def dup(self) -> list[Self]: ...


    def process[T: A | B | C](elem: T) -> list[T]:
    reveal_type(elem.dup)
    duplicated: list[T] = elem.dup()
    return duplicated


    process(A())
    process(B())
    process(C())


    The error is:

    main.py:25: error: Incompatible types in assignment (expression has type "list[A] | list | list[C]", variable has type "list[T]") [assignment]



    If I replace T: A | B | C with T: HasDup or T: (A, B, C), then the error is no longer reported.

    Is this a limitation of mypy? It seems to me like A | B | C is a subtype of HasDup.

    Continue reading...

Compartilhe esta Página