Protocol Or ABC In Python - When to Use Which One?

preview_player
Показать описание
When should you use protocol classes vs abstract base classes? Here's an example where I use both, talk about the trade-offs, and give you a suggestion of when to use each of them.

🎓 Courses:

👀 Channel code reviewer board:
- Yoriz
- Ryan Laursen
- Sybren A. Stüvel
- Dale Hagglund

🔖 Chapters:
0:00 Intro
2:01 Explaining the example
5:56 About abstract base classes
8:47 Protocols, nominal typing and structural typing
10:41 Using protocols
15:34 Splitting the Device class
20:05 When to use protocols vs abstract base classes

#arjancodes #softwaredesign #python

DISCLAIMER - The links in this description might be affiliate links. If you purchase a product or service through one of those links, I may receive a small commission. There is no additional charge to you. Thanks for supporting my channel so I can continue to provide you with free content each week!
Рекомендации по теме
Комментарии
Автор

Today, accidentally, I was searching "what is the difference between protocol and ABC" in google. And now I have this video! What a lucky day.

kyoungseoun
Автор

Dude, I am SO happy I found this channel a couple of days ago. These are exactly the kind of in depth discussions I've been searching for. It's the education I need at my skill level as a professional programmer. Thank you so much for doing these videos!

Tekay
Автор

Literally the best channel about Python Software Engineering! Right place to gain theoretical knowledge, proper mind-set, and last but not least, the experienced developer's line of reasoning. Thanks, I firmly appreciate your work and contribution!

mateuszsmendowski
Автор

The one advantage I see for protocols is cases where you might have overlapping function needs in multiple places which may be implemented by the same class. An example might be a tune up shop class that can perform services on anything with an engine that has a vehicle operator (car, motorcycle, tank, etc). Then, you have an entirely different class that is a tire shop class which can perform service on anything with tires that has a vehicle operator (car, motorcycle, bicycle, etc). In this case, a car can be serviced by the tune up shop or the tire shop but inheriting from both ABCs would cause a collision on the vehicle operator functions. On top of that, we can't have one combined ABC. Doing so would force the bicycle to implement all functions to meet the tune up shops needs and force the tank to implement all functions to support the tire shops needs, which wouldn't make sense since the bicycle can't go to the tune up shop. With protocols, these issues wouldn't arise because each shop would just require the things it needs in order to perform service.

dantemendez
Автор

One thing I find is often overlooked during the discussion of ABC vs Protocol, is that a Protocol is implemented as an ABC. (Technically, it's an extension of ABCMeta and ABC is just a helper class to simplify and keep code looking cleaner).
Nothing prevents you from creating a class that extends Protocol and defining abstract methods as you would on an ABC - you will get the same behaviour and in fact is how the default protocols are defined within the typing module itself.
This means depending on the exact use-case you can use either and/or both techniques within a single class definition.

stephenalderman
Автор

this will be at position #1 on Google for protocol vs abc. No matter how many searches I have done, nothing explained so clearly like this video. Thank you, Arjan!

alessandroferrari
Автор

Protocols seem to be a great way to achieve the Interface Segregation Principle of SOLID. Probably I'm going to use it more instead of only relying on ABCs. Thanks for the amazing video!

Pawlsolidus
Автор

Great video as always, Arjan! Although I would argue for a stronger conclusion: I feel that abc IS obsolete. First, you totally can explicitly use protocols as a base class (class Animal(Protocol): ... ; class Cat(Animal): ...). And second, you can even have a default method implementation in a protocol (although, I strongly advise against it). With that, abc doesn't seem to have any advantages in practice. I switched to protocols completely and don't regret it (more details if you google “sinavski abc vs protocols”).

sinavski_com
Автор

I think Protocol is meant to define an interface and use it only as type hinting for arguments.
Similar to Iterable, if an object has a couple of dunder methods, it means it adheres to the Protocols
ABC should be used to define relationships between superclasses and subclasses as mentioned in the of the video

hassaanalansary
Автор

Protocol seems more suited for distinguishing _traits_ with _trait objects_ . For example, you might define an interface that's really just an extension for objects like BeautyPrint with one method beauty_print() that just beautifully prints the object. Now, this isn't really meant to establish a hierarchy of beautifully printed objects so much as it gives an extension methods to those who need it. I don't think anything useful comes out of defining a function that takes a BeautyPrint.
That is, BeautyPrint might be a _trait_ (interface), but it's not a _trait object_ (doesn't represent a bunch of polymorphic types). Protocol might help prevent it from being a _trait object_ if you so choose.

VivekYadav-dsoz
Автор

Thanks very much for the clear explanation! I was searching for the difference between ABC and Protocols but was unable to find such a clear explanation!

marcopasopas
Автор

The more I use mypy and typing in python the more I like it! It really helps me when writing functions or methods to know in advance what parameters I am expecting and what I do have to return. And, of course, sometimes catches logical errors, too, before running, which is great.

mrswats
Автор

It looks like there is a lot of benefit to using Protocols over ABC, however, I still _really_ want to see Python supporting some way of explicitly defining that a class implements a Protocol, similar to TypeScript's Interfaces (I believe you've mentioned this in a previous video; it is still just as valid).

Also, I'd (personally) like to see type checkers raise warnings about missing methods/attributes from ABCs/Protocols at a class' definition instead of at the class' usage elsewhere in the code. If I forget to return a value in a statically-typed method, I expect to get a warning in the method definition, not when I attempt to call the method elsewhere in the code. There may be implementation issues for classes using methods from multiple files (which I've only ever read about), but I'm sure that's its own can of worms when it comes to best practices.

andrewglick
Автор

Great explanation of the use cases of these two Python features. Really appreciate your channel and the clear way you go through the logic of your code and programme design.

joel-eqtq
Автор

Edit: I wrote my comment before playing the video up to the end, where Arjan mentions both ISP and Uncle Bob. But I decided to leave the comment as is. Anyway, good job Arjan!

What happens here when Device abstract base class was replaced by two protocols seems like "I." from "S.O.L.I.D." principles. Namely "ISP = Interface Segregation Principle".
And hey, Python allows doing that without too much strict typing, but rather with "duck typing"!

Depending on the case this may be handy. And sometimes when more info is necessary when implementing a new class (to avoid mistakes ofc.) - would be to stick to ABC. Anyway, thanks for informative video 👍

WiktorWandachowicz
Автор

This channel became my go-to channel when I need some deep discussion. Excellent 🔥🔥🔥🔥

rajiththennakoon
Автор

Hi Arjan! Thank you for this excellent video and example. I think that you need multiple protocols in this example is a symptom of violating the single responsibility principle in the device class in the first place. The device class clearly has more than one responsibility. It actually reminds me of Uncle Bob's modem example where he shows how single responsibility violation looks like. The modem has the functionality "connect" and "disconnect" (responsibility 1) and "send" and "receive" data (responsibility 2) if I remember correctly. I think this example can be found in his book about agile software development. Anyway, great job!

robertbrummayer
Автор

Protocols are exactly the sort of solution that is needed for proper interface declarations in large systems with complex interactions. Fantastic. Thanks!

rdean
Автор

Your video finally made it clear how these two approaches differ, and why protocols are often the better choice. Thanks!

quiagonjin
Автор

The part I found the most impressing was how you used your IDE to edit the code, mostly with shortcuts.

ninobach