Structural interfaces
Annotate functions that accept any object implementing a known set of methods.
Python · Type Alias
typing.Protocol defines interfaces for structural subtyping. Static type checkers can accept any class that supplies the protocol’s declared members, even without explicit inheritance.
Protocol defines an interface for structural subtyping: a class can satisfy the protocol by providing the declared members, without inheriting from it. Static type checkers use this relationship; runtime checks require the separate runtime_checkable decorator and only test attribute presence.
class Protocol(Generic)from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
def shut(resource: SupportsClose) -> None:
resource.close()
class FileLike:
def close(self) -> None:
print("closed")
shut(FileLike())FileLike satisfies SupportsClose structurally because it defines the required close method; no explicit inheritance is needed.
Annotate functions that accept any object implementing a known set of methods.
Define reusable generic interfaces whose members preserve a type parameter.
Add optional runtime attribute-presence checks with @runtime_checkable.
typing.runtime_checkabletyping.Generictyping.TypeVar