|
|
Python Protocol and ABC
Author: Venkata Sudhakar
Python has two ways to define interfaces - contracts that a class must fulfil. Abstract Base Classes (ABC) use inheritance: you inherit from ABC and any subclass must implement all @abstractmethod methods or Python raises a TypeError at instantiation. Protocol uses structural typing (also called duck typing with type hints): a class satisfies a Protocol simply by having the right methods and attributes, with no inheritance required. ABC is the older, more strict approach. Protocol is the modern, more flexible approach introduced in Python 3.8. The key practical difference is that ABC requires you to explicitly inherit from the base class, which couples your code to the hierarchy. Protocol requires nothing - any class that happens to have the right methods is automatically considered compatible. This is particularly useful when you want to define a contract for third-party or legacy classes you cannot modify. Type checkers like mypy use Protocol definitions to catch mismatches at analysis time, not at runtime. The below example shows both approaches applied to a data migration pipeline where different source readers must conform to a common interface.
It gives the following output,
[{"id": 0}, {"id": 1}, {"id": 2}]
Is DataReader subclass: True
It gives the following output,
Satisfies protocol: True
Migration complete
# OracleReader never inherited from DataReader
# but isinstance() returns True because it has both required methods
# mypy also accepts OracleReader wherever DataReader is expected
When to use each: use ABC when you want strict enforcement that subclasses implement required methods, you control all the classes involved, and you want to share default implementations via the base class. Use Protocol when you want to write functions that work with any object having certain methods (including third-party classes you cannot modify), or when you want type safety without inheritance coupling. In modern Python code, Protocol is generally preferred for defining function parameter types.
|
|