protocol (subtyping)

In Python, a protocol defines a series of methods and attributes that a class must implement to be considered of a given type.

Protocols are a form of structural subtyping, which means that a type can be considered a subtype of a protocol if it provides the required methods and attributes, regardless of its actual inheritance chain. This is different from nominal subtyping, where a type must explicitly inherit from a base class to be considered a subtype.

Protocols are part of Python’s type hint system and are defined in the typing module.

Example

Here’s an example of using a protocol:

Python
from typing import Protocol

class Adder(Protocol):
    def add(self, x, y): ...

class IntAdder:
    def add(self, x, y):
        return x + y

class FloatAdder:
    def add(self, x, y):
        return x + y

# Usage
def add(adder: Adder) -> None:
    print(adder.add(2, 3))

add(IntAdder())
add(FloatAdder())

In this example, you define a class called Adder by inheriting from typing.Protocol. Adder has an .add() method, which defines the Adder protocol itself.

The IntAdder and FloatAdder classes implement the Adder protocol because they have an .add() method each. Therefore, you can use objects of either class as arguments to the add() function, which takes an Adder object as an argument.

Tutorial

Python Protocols: Leveraging Structural Subtyping

In this tutorial, you'll learn about Python's protocols and how they can help you get the most out of using Python's type hint system and static type checkers.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated May 7, 2025