ADocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
Protocol in Python is a base class provided by the typing module that enables structural subtyping (often referred to as static duck typing). Introduced in PEP 544, it allows developers to define an interface based on the presence of specific methods and attributes, rather than requiring explicit inheritance (nominal subtyping). If a class implements the members defined in a Protocol with matching type signatures, static type checkers recognize it as a subtype of that Protocol.
Syntax and Definition
A Protocol is defined by inheriting fromtyping.Protocol. The interface shape is established using type hints and the ... (Ellipsis) literal for method bodies, indicating that the implementation is deferred to the structural subtype.
Structural vs. Nominal Subtyping
Python traditionally relies on nominal subtyping via Abstract Base Classes (abc.ABC). In nominal subtyping, a class must explicitly declare its relationship to the interface. Protocol bypasses this requirement.
Runtime Behavior and Introspection
By default, Protocols exist purely for static type analysis (e.g., viamypy or pyright). They are erased at runtime. Attempting to use isinstance() or issubclass() against a standard Protocol will raise a TypeError.
To enable runtime introspection, the Protocol must be decorated with typing.runtime_checkable.
@runtime_checkable only verifies the presence of the required attributes and methods. Because Python does not enforce type hints at runtime, it cannot verify that the method signatures or attribute types of the instance actually match the Protocol’s definition.
Generic Protocols
Protocols can be combined withTypeVar to create generic structural interfaces. The Protocol class inherently supports the mechanics of typing.Generic.
Callable Protocols
Whiletyping.Callable is sufficient for simple function signatures, Protocols can define complex callable signatures by implementing the __call__ dunder method. This is necessary when a function type requires overloaded signatures, keyword-only arguments, or generic type variables that depend on each other.
Master Python with Deep Grasping Methodology!Learn More





