Abstract Base Classes (ABCs) and Protocols in Python

abc vs protocol

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.

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.

Here, Rectangle doesn’t need to inherit from SupportsArea β€” it just needs to match the shape of the protocol.

πŸ†š ABCs vs Protocols: Key Differences

FeatureAbstract Base ClassesProtocols
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.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *