Loading video player…

Exploring Protocols in Python (Overview)

In Python, a protocol specifies the methods and attributes that a class must implement to be considered of a given type. Protocols are important in Python’s type hint system, which allows for static type checking through external tools, such as mypy, Pyright, and Pyre.

Before there were protocols, these tools could only check for nominal subtyping based on inheritance. There was no way to check for structural subtyping, which relies on the internal structure of classes. This limitation affected Python’s duck typing system, which allows you to use objects without considering their nominal types. Protocols overcome this limitation, making static duck typing possible.

In this video course, you’ll:

  • Gain clarity around the use of the term protocol in Python
  • Learn how type hints facilitate static type checking
  • Learn how protocols allow static duck typing
  • Create custom protocols with the Protocol class
  • Understand the differences between protocols and abstract base classes

Resource linked in this lesson: Using Type Hints for Multiple Return Types in Python (Static Type Checkers)

Download

Course Slides (.pdf)

2.1 MB
Download

Sample Code (.zip)

1.5 KB

00:00 Hey there, my name is Rodrigo, and in this video course I’m going to take you through the journey of exploring protocols in Python. The objective of this course is for you to understand the point of protocols.

00:12 Why do you even need them? You will learn to create custom protocols in Python so that you can use them in your own code. You will build generic protocols for increased flexibility.

00:23 You’re going to learn about what members your protocols can have because you can also make some decisions there. And you will use inheritance suite protocols to see how to create hierarchies of protocols.

00:34 Now, this is not a beginner video course, so there are some prerequisites. To make the most out of this course, I need to make sure you are comfortable with OOP, inheritance, type hints, and with using static type checkers like mypy, Pyright, or another one if you use another static type checker.

00:54 And in case you need a refresher on static type checkers in this course, the demonstrations will be done using mypy. If you’re comfortable with it, you can use any other static type checker as long as it supports protocols, and in case you want to use the same type checker as the one used for the demos, go ahead and make sure you have mypy installed, and if you need a refresher, there’s a guide on static type checking with mypy that you can check out just to make sure you’re up to speed.

01:25 And as soon as you have that set up, we will dive right into protocols.

Become a Member to join the conversation.