Course contentsShow
← Python
Lesson 201 of 1,0603. Functions and ModularizationFree lesson

Using Protocols for Structural Subtyping

Learners will implement Protocols to define flexible interfaces that allow functions to accept any object possessing specific methods, enhancing code modularity.

In this lesson, you will learn how to use Protocols to define flexible interfaces that allow your functions to accept any object based on its structure rather than its inheritance hierarchy.

Moving Beyond Inheritance

Up until now, you have used type hints to ensure your functions receive the correct data types. Usually, this means checking if an object is an instance of a specific class. However, sometimes you don’t care what a class is, as long as it has the behavior you need—like a specific method. This is called structural subtyping (or "duck typing" with type safety).

Instead of forcing classes to inherit from a common base class, you define a Protocol. A Protocol acts as a blueprint: if an object has the methods defined in the Protocol, it is considered a valid type.

Implementing a Protocol

To create a Protocol, you import it from the typing module and define a class that inherits from it. Inside, you define the methods you expect, but you don't need to provide an implementation for them.

from typing import Protocol

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

def render_item(item: Drawable) -> None:
    item.draw()

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

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

render_item(Circle())  # Valid
render_item(Square())  # Valid

In this example, render_item doesn't know about Circle or Square. It only knows that it requires an object that possesses a draw method. Because both classes satisfy the structure of the Drawable protocol, the code works perfectly. This enhances modularity because you can introduce new types in entirely different modules without ever modifying the original code, as long as they implement the required method.

Unlike standard inheritance, you don't have to explicitly state that Circle implements Drawable. If the method exists, the type checker considers it a match. This keeps your code loosely coupled and highly reusable.

Key Takeaway: Protocols allow you to define what an object must do rather than what it is, enabling cleaner, more flexible code interfaces without the constraints of rigid class hierarchies.