Loading video player…

Creating Custom Protocols in Python

00:00 After understanding what protocols are useful for and what’s the point, really, the next step is knowing how to create custom protocols in Python. And the protocol really is just a class that inherits from typing.Protocol where typing is the module from the standard library.

00:16 So you define a class that inherits from Protocol, and in that class you define a series of methods that represent this behavior that the other classes must implement.

00:28 For example, for our walkers, it was walk() and run(). And for our swimmers, it was dive() and swim().

00:35 So this is all there is to it.

00:39 To create your first couple of protocols, what you can do is from typing, you can import Protocol, and now you will define the classes that inherit from this Protocol that you imported.

00:52 For example, to create a class for the walker protocol, what you do is you say class Walker(Protocol): because you want to inherit from Protocol and then you will define the methods that you require.

01:09 And when you do so, you need to type the full signature of the method with the parameters, and the type hints, and the return value type, to make sure you tell Python and static type checkers how those methods should look like when used.

01:24 And for example, for walk(), let’s just say that walk() accepts a destination: str with the name of wherever we are walking towards.

01:33 And the method returns nothing. Once you have the signature, you can just put an ellipsis there because you don’t have to say anything about the code. What you really want is just to prescribe the signature of the method, and you do the same thing for the method run().

01:50 Let’s say there’s also a destination: str

01:53 and there’s no code under it. And this defines the protocol. And just for the sake of exercising, pause the video and do the same thing for the swimmer protocol.

02:04 Alright, I’m assuming you gave it a go. It’s similar.

02:08 You create a class Swimmer(Protocol) and now you need to define a method dive(). Now you couldn’t have guessed, but let’s say that dive() accepts the depth the object is diving to and it also returns None.

02:25 And for the method swim(), it’s also going to accept a destination: str.

02:31 So this you have in front of you is the code for two different protocols. So you’ve created custom protocols, but if this feels underwhelming, it’s because you haven’t used them yet.

02:43 And that’s what you will learn in the next lesson.

Become a Member to join the conversation.