Course contentsShow
← Python
Lesson 563 of 1,0609. Type Safety and Code QualityFree lesson

Implementing Structural Subtyping with Protocols

You will define Protocols to enforce interface compliance based on object behavior rather than explicit class inheritance hierarchies.

In this lesson, you will learn how to use Protocols to define interface requirements based on what an object can do, rather than where it sits in a class hierarchy.

Beyond Explicit Inheritance

So far, you’ve used nominal subtyping, where a class must explicitly inherit from a parent to be considered its type. However, Python is a dynamic language that often relies on "duck typing"—if an object has the methods or attributes you need, it should work, regardless of its lineage. Protocols allow us to enforce this behavior while keeping our code statically type-checked.

Defining a Protocol

To define a Protocol, you import it from the typing module and define a class that inherits from Protocol. Inside, you specify the methods or attributes that "compliant" objects must provide.

Consider a scenario where you have different services that need to be "closable":

from typing import Protocol

class Closable(Protocol):
    def close(self) -> None:
        ...

def shutdown_service(service: Closable) -> None:
    service.close()

class Database:
    def close(self) -> None:
        print("Database connection closed.")

class FileHandler:
    def close(self) -> None:
        print("File handle released.")

# Both classes work because they share the 'close' method structure
shutdown_service(Database())
shutdown_service(FileHandler())

How It Works

Notice that Database and FileHandler do not inherit from Closable. They don’t even know Closable exists! As long as the class has a close method that accepts no arguments and returns None, a static type checker like mypy will verify that it satisfies the Closable protocol.

This approach creates a flexible, decoupled architecture. You define the behavior you expect, and any object that "quacks" like that behavior is automatically accepted by the type checker. It keeps your code safe without forcing you to build rigid, complex inheritance trees that make refactoring difficult later on.

Key Takeaway: Protocols allow you to enforce structural requirements on objects, enabling type-safe code that remains flexible by focusing on what an object does rather than what it is.