Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are abstract base classes redundant since Protocol classes were introduced?

I'm learning how to use Protocol classes that have been introduced in Python 3.8 (PEP 544).

So typing.Protocol classes are subclasses from ABCMeta and they are treated just like abstract classes are with the added benefit of allowing to use structural subtyping. I was trying to think of what I would use abstract base classes now and I'm drawing a blank.

What are the downsides of Protocol classes compared to ABCs (if any)? Maybe they come with a performance hit? Are there any specific cases where an ABC is still the best choice?

like image 912
pavel Avatar asked Nov 29 '25 20:11

pavel


1 Answers

I prefer ABCs beacuse they're explicit. With a Protocol someone reading the code may not know your class is intended to implement an interface in another module or deep in a dependency. Similarly, you can accidentally conform to a Protocol's signature, without conforming to its contract. For example, if a function accepts a

class Image(Protocol):
    def draw() -> None:
        ...

it's obviously not going to make sense with a

class Cowboy:
    def draw() -> None:
         ...

but the type checker would happily accept it.

like image 111
joel Avatar answered Dec 02 '25 10:12

joel



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!