Protocols vs ABCs in Python - When to Use Which One?

preview_player
Показать описание

In this video, I’m revisiting Protocols and ABCs in Python, essential for creating abstraction layers by defining interfaces. I covered this a while back, but it deserves a fresh look to clarify: what are the key differences, and when should you use each?

🔖 Chapters:
0:00 Intro
1:03 Short overview
1:53 Abstract Base Classes
5:39 Protocols
9:21 Making Protocols Behave Like ABCs
12:45 Conclusion
14:54 Outro

#arjancodes #softwaredesign #python
Рекомендации по теме
Комментарии
Автор

I generally prefer Protocols to ABCs. With an ABC I always feel like I'm telling the user "You must use my class as a Base class, or else!" A Protocol just specifies the interface requirements without getting pushy about the implementation. As far as concrete functions in an ABC, you can always code them as external functions taking the Protocol class as an argument (like "object oriented programming" in C or Go). Instance checking doesn't resonate with me, because if your code is overly dependent on that, maybe your design isn't so great.

cychoboy
Автор

Duck-typing is a dynamic typing strategy, Protocols are more akin to structural typing, since it's checked at "compile" time instead of at runtime.

hkejhkm
Автор

My practical conclusion to this question is basically, if the classes you want to interface with follow a strict hierarchy and are implemented with your specific application in mind, use ABC's.


If you want to interface with more generalized classes that may or may not be intended specifically with your application in mind, but you do care about them implementing some specific methods, use protocols.

TLDR: Protocols if you want to interface with other peoples classes ABC's to interface with your own classes

amos
Автор

I tend to use Protocol where implicit typing is most helpful; e.g., plugins or adapters. And don't forget the 3rd option - use neither. Polymorphism can be implemented without ABC. Just keep the differences in mind. E.g., without ABC you lose the @abstractmethod, et al mechanisms.

In general, we have learned over the years that deep type hierarchies lead to code that is less maintainable. Instead, we should prefer shallow hierarchies and only where needed - delegation is more preferable than inheritance.

Another great video!

klmcwhirter
Автор

For how I understand it:
ABC is just a groupment of whatever some classes have in commum in a separated class that holds those behaviours/methods and caracteristics/attributes.
Interface / protocol is a special abstract class that forces the subclasses to implement the behavior (implement the interface contract). We only talk about behavior (methods) here, we use it when we want to give some behavior to different objects withtou thinking about their types. It makes polymorphism quite easy as the subclasses can have different implementations of the methods.

Obud
Автор

As said in the documentation runtime_checkable is only used for isinstance and issubclass, and only check for attributes and methods, not the arguments of the methods, and even less their types. A type checker, like mypy, is needed for that. Python doesn't care about type annotations and Protocol is meant to be used with a type checker

TwidiAngel
Автор

I have been taking your videos for granted, but not anymore. You're doing some awesome work here, man!

olalekanbabawale
Автор

You have really gotten much much better at explaining and providing examples. Keep up the good work

bokistotel
Автор

LOL.. Love your videos.. here in the US, the saying about ducks is "If it walks like a duck and talks like a duck, then it's a duck". Your variation of 'tastes like a duck' make me chuckle.

cresentmoonyt
Автор

Curious why you turned off all type checking (pylance, etc.) for this video? Protocols are meant to catch things at "compile" time rather than runtime, as you said. It would make no sense to use Protocols without turning type checking on haha

Shrmp
Автор

As someone who also has a beard, I agreed with your assessment on videos are better with a beard and that includes pictures too. lol Keep up with your great videos. I enjoy learning something new about the language every time.

tacobuddy
Автор

I love this kind of videos. It's becoming increasingly clear to me that object-oriented programming or "traditional" object-oriented programming is a bit obsolete. Adopting a more TS-functional approach adapting SOLID principles and duck typing is the way forward at least you aren't creating a new framework or something like that.

Nobody
Автор

Very informative, please create more system design videos with hands on implementation

sanyk
Автор

Could you make a video or short on using callback protocols?

markoh
Автор

Can you do a video about isinstance()? Why it’s bad, how to avoid and situations where it is maybe rational?

christiansiegl
Автор

Hey, one of the cases where we can use the protocol is to describe a module:
>>>
from enum import Enum, auto
from typing import Protocol

from my_app.api.adaptors import grpc_adaptor, http_adaptor
from my_app.model.user import User


class APIType(Enum):
HTTP = auto()
GRPC = auto()


class ModuleAdaptor(Protocol):
@staticmethod
def get_user(id: int) -> User: ...


adaptors: dict[APIType, ModuleAdaptor] = {
APIType.HTTP: http_adaptor,
APIType.GRPC: grpc_adaptor,
}


def get_user(api: APIType, id: int) -> User:
return adaptors[api].get_user(id)
>>>
I don't know why, but if you want to write in a functional style, I think you can find a use for it.

typing.runtime_checkable does not work in this case, but we will get a hint in the IDE if the module does not comply with the protocol

Andrei_Golubov
Автор

It's easy to understand the difference between those. ABC is more like the classical OOP approach with "inheritance/abstract class". The protocol is more like the "trait implementation" Rust approach.

EulogySnowfall
Автор

Protocols are similar to Go interfaces where they are implicitly implemented. This is cool because you are lead to create abstractions when you need it and not when you foresee needing it. The end users get to decide what level of abstraction they want and not be forced into an abstraction level by whoever/wherever else the abstraction was created. "Don't design with interfaces, discover them" - Rob Pike (one of creators of Go), abstractions should be discovered, not created. This wouldn't be possible in many other languages cause of circular dependency etc.

AmazonBF
Автор

Yesterday I watched your video about ABC and quickly learned what it is and how to use it.
Now I watched this video about ABC and Protocols and forgot even what I learned yesterday 😂

sevdalink
Автор

I recently refactored a large plugin with a lot of Protocols . I gave up with the "Writable" explicit naming type and put a 'I' in from of all protocols, like it is done in java, C, etc ... e.g. IWritable . I found it cleaner to read and type at the end. Cheers

photaudiotech
visit shbcf.ru