Reputation: 374
Are there any benefits in inheriting from Protocols in Python?
eg.
class SampleProtocol(Protocol):
def do_something(self) -> int:
...
class Sample(SampleProtocol):
def do_something(self) -> int:
return 10
or should Sample
just be a class that implements the Protocol without explicitly inheriting from it?
Upvotes: 16
Views: 3962
Reputation: 1374
Another advantage, according to the PEP, is
type checkers can statically verify that the class actually implements the protocol correctly.
That is, it can warn you if Sample
doesn't have a conforming do_something
method.
Upvotes: 11
Reputation: 531908
Sample
can just implement the required method. There is no intent for the protocol to be part of a class's MRO; it is for static type-checking only.
Upvotes: 0