Sobes.tech
Junior — Middle

Explain the differences between using abstract classes and protocols in Python for defining interfaces.

sobes.tech AI

Answer from AI

In Python, abstract classes (ABC) and protocols (Protocol) can be used to define interfaces.

Abstract Classes (ABC)

  • Defined using the abc module and the @abstractmethod decorator.
  • Can contain both abstract methods and implemented methods.
  • Require subclasses to explicitly inherit from the abstract class and implement all abstract methods.
  • Used for strict control of class hierarchy.

Protocols (Protocol)

  • Introduced in the typing module (starting with Python 3.8).
  • Define an interface that a class should support but do not require explicit inheritance.
  • Support structural typing (duck typing): if an object has the required methods and attributes, it is considered to conform to the protocol.
  • Useful for flexible typing and type checking in static analyzers.

Briefly:

  • Abstract classes are nominal types of interfaces requiring inheritance.
  • Protocols are structural types of interfaces based on the presence of methods, without the need for inheritance.

Example of an abstract class:

from abc import ABC, abstractmethod

class MyInterface(ABC):
    @abstractmethod
    def do_something(self):
        pass

class Implementation(MyInterface):
    def do_something(self):
        print("Doing something")

Example of a protocol:

from typing import Protocol

class MyProtocol(Protocol):
    def do_something(self) -> None:
        ...

class Implementation:
    def do_something(self) -> None:
        print("Doing something")


def func(obj: MyProtocol):
    obj.do_something()

impl = Implementation()
func(impl)  # Works even though Implementation does not inherit from MyProtocol