Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting from Protocols in Python

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?

like image 654
Tyfingr Avatar asked Dec 18 '25 12:12

Tyfingr


1 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.

like image 100
Josiah Avatar answered Dec 21 '25 03:12

Josiah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!