Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Python · Type Alias

Protocol

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.

Since
3.8

How it works

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.

Syntax

class Protocol(Generic)

Key points

  • Protocol is the base class used to declare protocol interfaces.
  • Protocols let static type checkers accept objects based on the members they provide rather than explicit inheritance.
  • A protocol may be parameterized with type variables when the interface needs to preserve a value type.
  • Protocol annotations guide type checking; Python itself does not enforce ordinary annotations during execution.

Common mistakes

  • A protocol that is not decorated with @runtime_checkable cannot be passed to isinstance() or issubclass().

Example: Structural interface for closeable objects

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.

When to use it

Structural interfaces

Annotate functions that accept any object implementing a known set of methods.

Generic protocols

Define reusable generic interfaces whose members preserve a type parameter.

Runtime capability checks

Add optional runtime attribute-presence checks with @runtime_checkable.

  • typing.runtime_checkable
  • typing.Generic
  • typing.TypeVar

Source: typing — Support for type hints. Checked 2026-10-15.