Browse OOP reference
Types and contracts

What are protocols?

On this page

A protocol describes the operations that make a value usable in a role. A Python typing.Protocol can require close() so a static checker accepts suitable classes without explicit inheritance. Runtime-checkable protocols check limited aspects of member presence. They do not verify method signatures or promises about cleanup.

Worked example

Python
from typing import Protocol

class Flushable(Protocol):
    def flush(self) -> None: ...

class Batch:
    def __init__(self):
        self.pending = [1, 2]
    def flush(self) -> None:
        self.pending.clear()

def finish(writer: Flushable) -> None:
    writer.flush()

batch = Batch()
finish(batch)
assert batch.pending == []

PEP 544 on structural subtyping

Explore class relationships in the OOP Playground

What is method overloading?What is duck typing?How do modern languages approach object orientation?

All OOP questions

Search ObjectFAQ