Search code examples
pythonduck-typing

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?


Solution

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