Talk

Pythonic type hints with typing.Protocol

Friday, May 24

11:40 - 12:25
RoomLasagna
LanguageEnglish
Audience levelIntermediate
Elevator pitch

Duck typing is essential to idiomatic Python, but the first iterations of type hints did not support it. Eventually the typists gave us typing.Protocol. Using it is key to write well annotated Pythonic code.

Abstract

Many Pythonistas, this author included, reacted in shock and disbelief to the introduction of type hints in Python 3.5. We knew that duck typing was essential to idiomatic Python, but type hints did not support it until Python 3.8, with PEP 544 – Protocols: Structural subtyping (static duck typing) and the typing.Protocol special class.

Static duck typing, first popularized in the Go programming language, allows programmers to leverage the essential idea that “if it quacks like a duck then it is a duck”, when quacking behavior is required. In other words, it does not matter whether a class has the proper “ancestry” or DNA, as long as it implements the interface to play a role. With interfaces defined as typing.Protocol, the type checker can verify that an object’s class implements the required methods.

TagsBest Practice, Type-Hinting
Participant

Luciano Ramalho

Luciano Ramalho is the author of Fluent Python, a technical bestseller published in 9 languages. He started using Python professionally in 1998 and teaching it in 1999. Ramalho is a Fellow of the PSF and co-founder of the Python Brasil Association and of the Garoa Hacker Clube in São Paulo, Brasil.