User Tools

Site Tools


python_protocols

Protocol: the keystone of type hints

This proposal was accepted for a 25-minute talk at PyCon US 2021.

Description

The static type system supporting type hints in Python is becoming more expressive with each new PEP, but PEP 544—Protocols: Structural subtyping (static duck typing) is the most important enhancement since type hints were first introduced. The typing.Protocol special class lets you define types in terms of the interface implemented by objects, regardless of type hierarchies, in the spirit of duck typing—but in a way that can be verified by static type checkers and IDEs.

Without typing.Protocol, it was impossible to correctly annotate many APIs considered Pythonic, including many functions in the standard library itself. In this talk you will learn the concepts and benefits of static duck typing, through actual examples of increasing complexity taken from type hints of standard library functions in the official typeshed project.

Audience

This talk is for software developers who know the basics of type hints, but who may be struggling to annotate functions that are as flexible as built-ins like sorted—which accepts sequences of items of any existing or future type, as long as the items are comparable. Intermediate typing concepts like overload, generics and typevars will be explained as solutions to problems are presented. With this knowledge, participants will be able to create flexible and correctly annotated APIs, unconstrained by rigid type hierarchies.

The Typing Map

As part of this talk, I will explain this figure from Fluent Python, 2nd edition:

python_protocols.txt · Last modified: 2021/04/20 15:08 by luciano