Protocol Types in Python 3.8

🧩 A quick introduction to the new #Protocol #class in #Python 3.8 and how it enables structural typing.


In the previous installment, we have seen how to type annotations enable gradual typing in Python and some of the common typing patterns that Python developers use when writing code.

In this article, we're going to take a look at the new Protocol classes introduced in Python 3.8 and how it enables, even in typed contexts, structural typing, and other idiomatic patterns in Python.

What Is A Protocol

Protocol is a very generic word, both in regular language as well as in Computer Science. Most of us are probably familiar with it from hearing TCP Protocol, UDP Protocol or also HTTP Protocol. Dictionaries have also dedicated definitions for it:

A set of rules governing the exchange or the transmission of data between devices

Which indeed makes sense. All the examples listed above are communication protocols between two remote devices with a set of rules that are governing the transmission. In the case of TCP, for instance, the protocol mandates the shape of the message, the possible operations, the error policies as well as the rules for possible retransmission of a message.

On the other hand, it might be kind of weird for people to talk about protocols in a programming language. After all, there is no communication involved in a program, so what is the meaning of it?

We can answer the question by taking a look at another more generic definition that is not coupled with computer science:

The accepted or established code of procedure or behavior in any group, organization, or situation. (New Oxford Dictionary)

Let's notice the difference with the previous definition we found above:

  • No devices involved.
  • No data transmission involved.
  • No data involved, per se.

In fact, the nature of the protocol we're going to be talking about today. By removing some of the constraints of the previous definition, it is possible to reason about protocols in the context of a programming language.