Inherting from Protocols in Python

Viewed 282

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?

2 Answers

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.

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.

Related