[Python] Mypy error, [Type] has no attribute [method]

Discussão em 'Python' iniciado por Stack, Maio 17, 2025.

  1. Stack

    Stack Membro Participativo

    I have an abstract base class:

    import abc
    import typing as t

    class Parent1(abc.ABC):
    ...


    And a subclass of that abstract base class above, that is itself an abstract base class:

    class Parent2(Parent1):

    @abc.abstractmethod
    def method2(self) -> None:
    ...



    And now a concrete child class that inherits from Parent2 abstract class:

    class Child1(Parent2):

    def method2(self) -> None:
    pass


    And another concrete child class that inherits from Parent1 class:

    class Child2(Parent1):
    pass


    Now I'm trying to make a generic container to holds all instances of Parent1 class

    T = t.TypeVar("T")

    class Container(t.Generic[T]):

    def __init__(self) -> None:
    self._containers: t.Dict[str, T] = {}

    def add_item(self, name: str, item: T) -> None:
    # reveal_type(item)
    self._containers[name] = item

    def get_item(self, name: str) -> T:
    return self._containers[name]


    container: Container[Parent1] = Container()

    container.add_item("child1", Child1())
    container.add_item("child2", Child2())


    child1 = container.get_item("child1")
    # assert isinstance(child1, Child1)
    # reveal_type(child1) # Revealed type is "generic1.Parent1"

    child1.method2()
    # t.cast(Child1, child1).method1()


    When trying to run mypy --strict without assert isinstance or cast, it report an error saying that error: "Parent1" has no attribute "method2"

    How to fix the problem without using assert isinstance or typing.cast, or even without the # type: ignore comment?

    Continue reading...

Compartilhe esta Página