Sobes.tech
Junior — Middle

What are the advantages and disadvantages of using protocols in Python to define interfaces?

sobes.tech AI

Answer from AI

In Python, protocols from the typing module allow defining interfaces at the type level without the need to inherit from specific base classes. This supports the concept of "structural typing".

Advantages:

  • Enable describing interfaces that objects must implement without rigid inheritance hierarchies.
  • Improve code readability and maintainability by making expected methods and properties explicit.
  • Supported by static type analyzers (e.g., mypy), which helps catch errors during development.

Disadvantages:

  • Protocols do not affect runtime behavior; they are only for static checking.
  • Can complicate code if too many protocols or complex hierarchies are used.
  • It is not always obvious if an object conforms to a protocol without explicit inheritance, which can make code harder for beginners to understand.

Example of using a protocol:

from typing import Protocol

class Drawable(Protocol):
    def draw(self) -> None:
        ...

class Circle:
    def draw(self) -> None:
        print("Drawing a circle")

class Square:
    def draw(self) -> None:
        print("Drawing a square")


def render(shape: Drawable) -> None:
    shape.draw()

circle = Circle()
square = Square()

render(circle)  # Drawing a circle
render(square)  # Drawing a square

Thus, protocols in Python are a powerful tool for defining interfaces, especially useful in large projects with dynamic typing.