Is typing.Protocol with composition rather than inheritance even possible?

We are instructed to use inheritance with typing.Protocol. So like this…

import typing

class MyProtocolClass(typing.Protocol):
    ...

Is it possible to use composition instead? So like…

import typing

class MyProtocolClass:
    def __init__(self):
        self.my_protocol = typing.Protocol()

Am I completely misunderstanding the whole concept of Python’s typing.Protocol thing?

What would that mean? It’s not meaningful to just instantiate Protocol.

@Jelle, please elaborate on It’s not meaningful to just instantiate Protocol.

Have you read PEP 544 which defines Protocol types? Or there is some more user-friendly explanation in the mypy docs.
To me, it’s not clear what you want to accomplish and how it might relate to Protocol.

Protocol needs to be inherited to mark the child class as a protocol, and that’s also where you declare the signature of the child class. The Protocol class by itself doesn’t mean much at all.

2 Likes

@EpicWink, thanks for this. Now I understand.