[Python] Explicitly declared protocol on child fails with "Protocols cannot be instantiated"

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

  1. Stack

    Stack Membro Participativo

    Please help me understand why this code fails.

    from typing import Protocol

    class Base:
    pass

    class MyProto(Protocol):
    def hello(self) -> None:
    pass

    class Child(Base, MyProto):
    def __init__(self) -> None:
    super().__init__() # TypeError: Protocols cannot be instantiated

    def hello(self) -> None:
    return print("hello")

    Child()


    Error:

    TypeError: Protocols cannot be instantiated


    I understand that a protocol should not be instantiated, but isn't this the responsibility of the language to avoid this error?
    Or is there another way to explicitly implement a Protocol on a child class?

    Yes, we can avoid super and it will work:

    class Child(Base, MyProto):
    def __init__(self) -> None:
    Base.__init__(self)


    But it's more common (and easier) to use super.

    It feels like something is broken in the language.

    I am using Python 3.9.

    Continue reading...

Compartilhe esta Página