[Python] Mypy issue with generics and overload

Discussão em 'Python' iniciado por Stack, Junho 4, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to add types to my code and now have problem. Below is minimal version of code. I cant take a point why B[str] | B[bytes] is incompatible with A[T]. Two last errors is also unexcepted for me (but they will be fixed if change signature .get_object(...) -> A[T]

    Why my solution is wrong and what should I change?

    from abc import abstractmethod
    from typing import TypeVar, overload, Generic, Literal

    T = TypeVar('T', str, bytes)
    class A(Generic[T]):
    pass

    class B(A[T]):
    def __init__(self, x: T) -> None:
    self.x: T = x

    class C(A[bytes]):
    def __init__(self, x: bytes) -> None:
    self.x: bytes = x

    class AbstractCreator:
    @abstractmethod
    def get_object(self, x: Literal["bytes", "str"]) -> A[T]:
    ...

    class BCreator(AbstractCreator):
    @overload
    def get_object(self, x: Literal["bytes"]) -> B[bytes]:
    ...

    @overload
    def get_object(self, x: Literal["str"]) -> B[str]:
    ...

    def get_object(self, x: Literal["bytes", "str"]) -> A[T]:
    if x == "bytes":
    return B(b"test")
    if x == "str":
    return B("test")


    but mypy get an error

    main.py:22: error: Signature of "get_object" incompatible with supertype "AbstractCreator" [override]
    main.py:22: note: Superclass:
    main.py:22: note: def [T: (str, bytes)] get_object(self, x: Literal['bytes', 'str']) -> A[T]
    main.py:22: note: Subclass:
    main.py:22: note: @overload
    main.py:22: note: def get_object(self, x: Literal['bytes']) -> B[bytes]
    main.py:22: note: @overload
    main.py:22: note: def get_object(self, x: Literal['str']) -> B[str]
    main.py:32: error: Incompatible return value type (got "B[bytes]", expected "B[str]") [return-value]
    main.py:34: error: Incompatible return value type (got "B[str]", expected "B[bytes]") [return-value]

    Continue reading...

Compartilhe esta Página