17

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 2

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly! If you intend that a class follow a particular protocol, then saying so in your code (a) is self-documenting for future readers of your code, and (b) allows the compiler to check that your intentions are met.
0

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.

2 Comments

python.org/dev/peps/pep-0544/… looking at the pep it looks like it's a solid way of using protocols.
The question is not whether you can do it without inheritation, but the question is whether there are benefits in still using inheritation anyway. You do not really answer that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.