2022-07-13 –, Liffey B
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.
Outline
- What are protocols:
- Structural vs nominal typing
- Static duck typing
-
Difference between ABCs and protocols
-
Examples
- Simple example
- Extending protocols
-
Use cases
- 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.
some
Expected audience expertise: Python:some
Abstract as a tweet:Python Protocols - Structural subtyping for decoupled and Pythonic code
I'm a software engineer currently living in USA. I enjoy learning new languages and learning about them.