Types

Protocols

Protocol describes required behavior for structural typing.

A protocol names required behavior. The ellipsis marks the method body as intentionally unspecified, similar to an interface declaration.

Source

from typing import Protocol

class Greeter(Protocol):
    def greet(self) -> str:
        ...

print(Greeter.__name__)

Output

Greeter
OBJECTread()write()close()structuralPROTOCOLread()close()
An object satisfies a protocol structurally — by having the required methods — not by inheriting it.

A class can satisfy the protocol without inheriting from it. Person has a compatible greet() method, so it has the right shape for static type checkers.

Source

class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        return f"hello {self.name}"

print(Person("Ada").greet())

Output

hello Ada

Use the protocol as an annotation at the API boundary. The function only cares that the object can greet; it does not care about the concrete class.

Source

def welcome(greeter: Greeter):
    print(greeter.greet())

welcome(Person("Ada"))

Output

hello Ada

Notes

See also

Run the complete example

Example code

Expected output

hello Ada
Greeter

Execution time appears here after you run the example.