Python is a dynamically typed language, but as your codebase grows, ensuring consistency and correctness becomes critical. Two powerful tools that help in defining and enforcing interfaces are Abstract Base Classes (ABCs) and Protocols. While they may seem similar at first glance, they serve different purposes and operate in distinct ways.
πΉ What Are Abstract Base Classes (ABCs)?
Abstract Base Classes (ABCs) are part of the abc module in Pythonβs standard library. They allow you to define a base class with abstract methods that must be implemented by any subclass.
β Use Case:
ABCs are ideal when you want to enforce a class hierarchy and ensure that derived classes follow a specific structure.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
If a subclass does not implement the area() method, instantiating it will raise a TypeError.
.
πΉ What Are Protocols?
Protocols come from the typing module (typing.Protocol) and represent a form of structural subtyping. This means a class is considered a subtype if it has the required methods and properties, regardless of inheritance.
β Use Case:
Protocols are great for duck typing with type safety. You can define expected behaviors without enforcing explicit inheritance.
from typing import Protocol
class SupportsArea(Protocol):
def area(self) -> float:
...
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self) -> float:
return self.width * self.height
def print_area(shape: SupportsArea):
print(f"Area: {shape.area()}")
print_area(Rectangle(3, 4)) # Valid because Rectangle has an area() method
Here, Rectangle doesn’t need to inherit from SupportsArea β it just needs to match the shape of the protocol.
π ABCs vs Protocols: Key Differences
| Feature | Abstract Base Classes | Protocols |
|---|---|---|
| Inheritance Required | β Yes | β No |
| Enforced at Runtime | β Yes | β οΈ No (Type check only) |
| Duck Typing Friendly | β No | β Yes |
| Typing Support | β Yes | β Yes |
| Use in Static Analysis | β Yes | β Yes (via mypy or Pyright) |
π‘ When to Use What?
- Use ABCs when:
- You need to enforce an interface at runtime.
- You’re working with classic OOP and inheritance.
- You need control over instantiation and hierarchy.
- Use Protocols when:
- You prefer structural typing.
- You want flexibility with interfaces.
- You rely on static type checking but don’t want to enforce runtime behavior.
β Conclusion
Both Abstract Base Classes and Protocols are powerful tools for interface definition in Python. Choose ABCs for strict runtime enforcement, and Protocols for flexible, duck-typed interfaces. In modern Python, especially when using static type checkers like mypy, Protocols can make your code both robust and expressive β all without unnecessary inheritance chains.

