Protocols - Static duck typing for decoupled code
- Liffey B
- Start (Dublin time):
- Start (your time):
- 30 minutes
Python introduces Protocols to support static duck typing, where static type checkers (mypy) and other tools can verify code correctness prior to runtime.
This was added in order to circumvent explicitly inheriting from ABCs (Abstract base classes) which is "unpythonic and unlike what one would normally do in idiomatic dynamically typed Python code" - according to PEP 544.
We will explore the different use cases for Protocols and how to use them correctly.
What are protocols:
- Structural vs nominal typing
- Static duck typing
- Difference between ABCs and protocols
- Simple example
- Extending protocols
- Dynamically typed code
- Library types
During this talk we will go over Protocols and how they can be employed to achieve better code. Take the following code snippet as an example:
from typing import Sized, Iterable, Iterator class Bucket(Sized, Iterable[int]): ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[int]: ...
The problem here is that you must explicitly inherit these bases classes to register them as subtypes of their parents.
This is particularly difficult to do with library types as the type objects may be hidden deep in the implementation of the library. Also, extensive use of ABCs might impose additional runtime costs.
Consider the following snippet as a solution:
from typing import Iterator, Iterable class Bucket: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[int]: ... def collect(items: Iterable[int]) -> int: ... result: int = collect(Bucket()) # Passes type check
Protocols enable you to pass static type checking implicitly.