Course contentsShow
← Python
Lesson 651 of 1,06010. Advanced Language FeaturesFree lesson

Implementing Structural Subtyping for Duck Typing

Understand how Python's static type checker validates objects based on their structure rather than their explicit type hierarchy or base classes.

In this lesson, you’ll learn how to use typing.Protocol to enforce structural subtyping, allowing your code to verify that objects possess the specific attributes or methods it needs, regardless of their class hierarchy.

From Duck Typing to Structural Subtyping

Python is famous for "Duck Typing": if it walks like a duck and quacks like a duck, it’s a duck. Traditionally, this means you just call a method and hope the object supports it. However, as your codebase grows, you might want to catch potential errors before you run your code. This is where Structural Subtyping comes in.

Instead of requiring an object to inherit from a specific base class (Nominal Subtyping), you define a Protocol. A class automatically "implements" this protocol if it happens to have the required structure.

Practical Implementation

Imagine you have a function that processes items by calling a .save() method. Rather than forcing every class to inherit from a Savable base class, you define a protocol:

from typing import Protocol

class Savable(Protocol):
    def save(self) -> None:
        ...

class DatabaseRecord:
    def save(self) -> None:
        print("Saving to DB...")

def process_and_save(item: Savable):
    item.save()

# This works because DatabaseRecord "looks like" a Savable
process_and_save(DatabaseRecord())

How it Works

When you define Savable as a Protocol, the static type checker (like mypy or the one built into your IDE) doesn't check if an object inherits from Savable. Instead, it checks the structure: "Does this object have a save method that accepts no arguments?"

If you pass an object that lacks a save method, the type checker will flag an error immediately. You gain the safety of static typing without the rigid requirement of class hierarchies. This allows you to integrate objects from third-party libraries—which you cannot modify to add base classes—into your type-safe pipelines seamlessly.

Key Takeaway: Structural subtyping via Protocol allows you to define expected behavior based on an object's actual methods and attributes, providing the safety of explicit types while preserving the flexibility of Python's duck-typing philosophy.