In this lesson, you will learn how to enforce object behavior using Protocol classes to define structural interfaces without needing formal inheritance.
The Problem with Inheritance
In Python, we often use inheritance to ensure a class provides specific methods. However, forcing every object into a strict class hierarchy can lead to rigid, bloated codebases. Sometimes, you don't care what an object is, only that it "looks" and "acts" a certain way—a concept known as Duck Typing.
Introducing Protocols
A Protocol allows you to define an expected interface—a set of methods or attributes that an object must possess—without requiring that object to inherit from your interface class.
Consider a system where we need to export data. Instead of forcing every class to inherit from an Exporter base class, we define a Protocol:
from typing import Protocol
class Exportable(Protocol):
def export(self) -> str:
...
def process_data(item: Exportable):
print(f"Processing: {item.export()}")
class PDFFile:
def export(self) -> str:
return "PDF Content"
# Even though PDFFile doesn't inherit from Exportable,
# it satisfies the interface structurally.
process_data(PDFFile())
Why Use Protocols?
- Loose Coupling: Your code remains decoupled because objects don't need to be part of a shared inheritance tree.
- Static Type Checking: If you use tools like
mypy, they will automatically verify that any object passed toprocess_dataactually contains anexportmethod. If it doesn't, the type checker flags an error before you even run your code. - Flexibility: You can define protocols for third-party classes that you cannot modify or force to inherit from your own base classes.
By using Protocol, you are essentially saying: "I don't care about your ancestry; I only care that you implement the methods I need to get the job done." This makes your codebase significantly more modular and easier to test.
Key Takeaway: Protocol classes allow you to define structural interfaces that enforce required behaviors without the constraints of explicit class inheritance.