Sobes.tech
Junior — Middle

In what situations is it preferable to use protocols instead of abstract base classes when developing interfaces in Python?

sobes.tech AI

Answer from AI

In Python, protocols are preferred over abstract base classes (ABCs) in situations where flexibility and duck typing are important — that is, when you need to define an interface that can be implemented by different classes without explicit inheritance.

Protocols allow you to describe a set of methods and attributes that an object should have, but do not require inheritance from a specific base class. This is convenient if you want different objects with different hierarchies to be interchangeable, as long as they conform to the protocol.

Example situation:

  • You write a function that works with any object that has a read() method. Instead of requiring inheritance from an abstract class, you can define a protocol with a read() method and accept any objects that conform to this protocol.

This improves compatibility and reduces coupling in your code.

Example of a protocol:

from typing import Protocol

class Readable(Protocol):
    def read(self) -> str:
        ...

def process(reader: Readable):
    data = reader.read()
    print(data)

Here, any object with a read method can be passed to process, even if it does not inherit from Readable.