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

Sdílet
Vložit
  • čas přidán 31. 05. 2024
  • 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.
    The code I worked on in this video is available here: github.com/ArjanCodes/2021-pr....
    💡 Here's my FREE 7-step guide to help you consistently design great software: arjancodes.com/designguide.
    🎓 Courses:
    The Software Designer Mindset: www.arjancodes.com/mindset
    The Software Designer Mindset Team Packages: www.arjancodes.com/sas
    The Software Architect Mindset: Pre-register now! www.arjancodes.com/architect
    Next Level Python: Become a Python Expert: www.arjancodes.com/next-level...
    The 30-Day Design Challenge: www.arjancodes.com/30ddc
    🛒 GEAR & RECOMMENDED BOOKS: kit.co/arjancodes.
    💬 Join my Discord server here: discord.arjan.codes
    🐦Twitter: / arjancodes
    🌍LinkedIn: / arjancodes
    🕵Facebook: / arjancodes
    👀 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!

Komentáře • 288

  • @ArjanCodes
    @ArjanCodes  Před 2 lety +20

    Get my FREE 7-step guide to help you consistently design great software here: arjancodes.com/designguide.

    • @dijakroot
      @dijakroot Před 3 měsíci

      Great content, Arjan. I've been trying downloading the design guide that you mentioned, but sadly the link from the email doesn't work.

  • @kyoungseoun
    @kyoungseoun Před 2 lety +118

    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.

    • @ArjanCodes
      @ArjanCodes  Před 2 lety +6

      I posted it just in time ;)

    • @atahirince
      @atahirince Před 2 lety +5

      Big brother is watching you …

    • @__lasevix_
      @__lasevix_ Před rokem +4

      So Google does use our data to improve our lives!

  • @Tekay37
    @Tekay37 Před 2 lety +65

    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!

    • @EinsteinNewtonify
      @EinsteinNewtonify Před rokem

      feels strange that I cannot find these info using just google.

    • @hoseynamiri
      @hoseynamiri Před 9 měsíci

      @ArjanCodes I need a book to study all these nice coding principles and unwritten rules of efficient python programming. Is there any reference out there?

  • @mateuszsmendowski2677
    @mateuszsmendowski2677 Před rokem +36

    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!

  • @dantemendez3743
    @dantemendez3743 Před 2 lety +16

    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.

  • @rdean150
    @rdean150 Před 2 lety

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

  • @stephenalderman254
    @stephenalderman254 Před 2 lety +30

    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.

    • @ArjanCodes
      @ArjanCodes  Před 2 lety +6

      Good point, Stephen!

    • @OmbraDiFenice
      @OmbraDiFenice Před 2 lety +1

      this makes a lot of sense and it's actually what I was imagining from the point of view of implementing something similar to protocols in a language like C++: you could do it by redefining the same data structure in the various compilation units and then use this redefinition as a normal abstract base class. This also fits nicely with python's "same structure" concept - of course paying attention to padding if you're redefining it just partially or if you have more levels of inheritance.
      Maybe the parallelism is not quite correct, for example I feel that what @Vivek said about type traits is more technically precise (I'm not expert on traits), but it's a way to see things I guess :D

    • @matthiasschuster9505
      @matthiasschuster9505 Před rokem

      @@ArjanCodes would you make a video on this?

  • @TheMako101
    @TheMako101 Před 5 měsíci

    A truly excellent video, as always, you've gone way above and beyond simply explaining the concept, and outlined excellent use cases and way of thinking to know when to pick which one. thanks again, Arjan :)

    • @ArjanCodes
      @ArjanCodes  Před 5 měsíci

      I'm really glad my video was helpful!

  • @alessandroferrari2166
    @alessandroferrari2166 Před 2 lety +1

    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!

  • @imadetheuniverse4fun
    @imadetheuniverse4fun Před 2 lety +1

    Another extremely informative video, thank you. Did not expect being able to split up Protocols like that, but it makes total sense. Will definitely be incorporating them more now.

  • @rajiththennakoon7392
    @rajiththennakoon7392 Před 2 lety +1

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

  • @joel-eq8tq
    @joel-eq8tq Před 2 lety +2

    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.

    • @ArjanCodes
      @ArjanCodes  Před 2 lety

      Thank you Joel, happy to hear you like the channel!

  • @mrswats
    @mrswats Před 2 lety +2

    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.

  • @ninobach7456
    @ninobach7456 Před 5 měsíci +2

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

  • @brokenbe
    @brokenbe Před 9 měsíci

    Hi Arjan, glad to find this lecture, love it. Ty!

  • @IgorRibeiroBraga
    @IgorRibeiroBraga Před 2 lety

    Great explanation. Very good work! Congrats!!

  • @marcopasopas
    @marcopasopas Před rokem +1

    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!

  • @robertbrummayer4908
    @robertbrummayer4908 Před 2 lety +2

    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!

  • @Archfile375
    @Archfile375 Před rokem

    Very interesting, this is exactly a paradigm for a driver collection/service that I hacked very poorly together to test a piece of hardware with the intention of wrapping that driver up in a connection management service. This a most fascinating look at a much better way of handling my idea. Thank you very much for the work, not just because it hit on a topic that was directly interesting to me but because you've done such a great job of making videos on non-trivial topics in general

  • @nomex9829
    @nomex9829 Před 11 měsíci

    I'll have to watch the video a couple more times, but it's brilliant stuff. You explained it so well I can't thank you enough.

  • @vxsniffer
    @vxsniffer Před 2 lety +1

    most of Python tutorials are basics... your channel is very pleasant discovery ;-)

  • @WiktorWandachowicz
    @WiktorWandachowicz Před 2 měsíci

    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 👍

  • @ohandyya
    @ohandyya Před 2 lety +1

    Thanks for creating and sharing this video. This is a topic that confused me for quite some time.Your explanation is very clear. Love it.

  • @Golgafrincham
    @Golgafrincham Před 2 lety

    Do you use some kind of plugin or extension for the highlighting? I cloned your repo and commented out the "connect"-method in Huelight as you do but I do not get any notice at all that the HueLight is not following the expected Protocol. I only get an error when running saying: "AttributeError: 'HueLightDevice' object has no attribute 'connect'"🤔

  • @Pawl0solidus
    @Pawl0solidus Před rokem +12

    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!

    • @ArjanCodes
      @ArjanCodes  Před rokem +1

      Thanks Paulo, happy you’re enjoying the content!

    • @hoseynamiri
      @hoseynamiri Před 9 měsíci

      ​@@ArjanCodesI need a book to study all these nice coding principles and unwritten rules of efficient python programming. Is there any reference out there?

  • @fluidmarble
    @fluidmarble Před 2 lety

    Arjan, I love your channel. thank you so much for the high quality. I have no doubt your channel will be recommended in CS courses within a year

  • @hassaanalansary
    @hassaanalansary Před 2 lety +10

    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

    • @cheaterman49
      @cheaterman49 Před 2 lety +1

      I agree, and it goes beyond that IMHO ; sometimes it is impossible to accurately define a function with pure type hinting (say when a method takes a coroutine as argument), and you can instead implement a Protocol's `__call__` method to accurately describe it.

    • @sirmidor
      @sirmidor Před rokem

      @@cheaterman49
      >(say when a method takes a coroutine as argument)
      Just use typing.Coroutine (can be parameterized too)?

  • @josephlyons3393
    @josephlyons3393 Před 2 lety +1

    Always enjoy your videos. Would love a video on how you personally set up each of your python projects within VS Code.

  • @Nobody313
    @Nobody313 Před rokem +2

    I love duck typing filosofy/pattern. It keeps the things so simple and organic.

  • @greob
    @greob Před 3 měsíci

    Great demonstration, thanks for sharing!

    • @ArjanCodes
      @ArjanCodes  Před 3 měsíci

      I'm glad to hear you enjoyed the video! Thank you for the comment.

  • @Ziggity
    @Ziggity Před 2 lety

    I was literally debating with myself which of the two will be more suitable for a project I have at work when I opened CZcams. Impeccable timing and excellent video 👌🏽

  • @uwegenosdude
    @uwegenosdude Před 3 měsíci

    Thanks again for your very helpful video which explains the differences between protocols and ABCs.

    • @ArjanCodes
      @ArjanCodes  Před 3 měsíci

      Glad the content was helpful!

  • @quiagonjin108
    @quiagonjin108 Před 2 lety +1

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

    • @ArjanCodes
      @ArjanCodes  Před 2 lety

      You’re welcome, glad it was helpful!

  • @patricktarnaud
    @patricktarnaud Před 2 lety

    Great explication ! Thanks

  • @matiaszulberti9996
    @matiaszulberti9996 Před 2 lety

    Thank you so much! The explanation is so clear and the content super useful.

  • @69AndyM
    @69AndyM Před 2 lety +1

    Love this video. Thanks for touching on the differences between the two and showing examples. :)
    Love your Python videos. I code primarily in Python and in Golang. Wish there was a teacher like you for golang! It's an untapped market imo.

    • @ArjanCodes
      @ArjanCodes  Před 2 lety +1

      Thanks Andrew, glad you like the videos! I’m not a Go expert (yet ;) ), but I’m intrigued by it.

  • @juanjoseexpositogonzalez1126

    Really good explained. It's given me some good piece of advice for an app I'm refactoring.

  • @shilinwang1847
    @shilinwang1847 Před rokem

    crystal clear, thanks for the video!

  • @thallysrc
    @thallysrc Před 2 lety

    best channel with the best content available with the best coder

  • @endab5517
    @endab5517 Před 2 lety +1

    This video brought attention to the letter board for this new subscribers. Now we need to go back to find your hard work! Thank you for the great content. Take care

    • @ArjanCodes
      @ArjanCodes  Před 2 lety

      Thank you, glad you like the videos!

  • @VivekYadav-ds8oz
    @VivekYadav-ds8oz Před 2 lety +10

    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.

    • @rajatsethi
      @rajatsethi Před 2 lety

      Other newer languages have this feature like Rust

  • @JoaoSantos-lv4rc
    @JoaoSantos-lv4rc Před rokem

    listened to this again for lunch and already applied protocols succesfully for the first time:)). thanks again Arjan.

  • @sinavski_com
    @sinavski_com Před rokem +5

    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”).

    • @EvenTheDogAgrees
      @EvenTheDogAgrees Před 5 měsíci

      Nice article, but relies a bit too much on external resources for context, rather than providing the context directly. External resources are prone to link rot, robbing the reader of your article of the required context. They also require a context switch: the reader needs to open the link and read the (often lengthy) article, which probably covers far more than the limited coverage that understanding of yours requires. Hopefully it doesn't also reference external resources of its own, or the reader will have absorbed dozens of overlapping articles before they're ready to return to yours. And then the reader needs to come back to your article, offload the discussion from the external article, and pick up the train of thought that was interrupted when they were sent off elsewhere.
      I think it's better if information is self-contained. Referencing external resources for a more in-depth treatment of the context is OK, but the parts that are necessary for a proper understanding of the primary article should be _in_ the primary article, even if in shortened form and lacking otherwise important nuance that just isn't relevant in the context of the primary article. Also, links where the anchor text is just "here" are useless once the link target disappears. The reader has no idea what the title was, who the author was, and will be unable to retrieve the information even if it did survive elsewhere, as they have zero clues on what to search for. And that's something I just realised I should also start applying to my own writings, as I tend to do the same. 😂
      Anyway, don't take this as a "you suck" criticism; it is meant in a constructive way. If I thought your blog post was not worth my time, or if I didn't appreciate your effort, I wouldn't have bothered responding. I love it when people freely share their knowledge, moreso when they're knowledgeable about the subject and cover things that go beyond the introductory matter. Your blog post was certainly appreciated.

  • @almoni127
    @almoni127 Před 2 lety +1

    Thanks for the video!
    For me python's dynamic typing seems as a major design flaw, and ABC and protocols look like convoluted afterthoughts.

  • @smann43231816
    @smann43231816 Před 2 lety

    Another great tutorial. Thanks again

  • @kevon217
    @kevon217 Před rokem

    Your videos never disappoint!

  • @joem8251
    @joem8251 Před 2 lety

    Thank you for presenting this topic! Last week I spent more time than 23:45 trying to figure this out.

    • @ArjanCodes
      @ArjanCodes  Před 2 lety +1

      You’re welcome Joe, glad you liked it! I also spent way more time than 23:45 to figure it out before I recorded the video, so I totally get it 😊.

  • @hotlinkster123
    @hotlinkster123 Před 2 lety +137

    I'm still not convinced protocols are better than ABC's when used in the way shown in the video. I will address the 2 main points:
    1) Removing inheritance and imports: This removes the explicit relationship between the parts of code, and turns it implicit. You say it reduces coupling; yes in the actual program, but it only moves the coupling into the brain of the programmer, as they have to know about which protocols the class should implement. I find this bad because then you are relying on the programmer to ensure the protocol is correctly followed, and computers are better at catching errors than people.
    2) Splitting up the protocol and multiple inheritance: Splitting up the interface can be done with ABC's, but this is supposed to be bad because multiple inheritance is then needed. I don't see a problem with multiple inheritance though. Sure it can get messy quick if the defined ABC's are bad, but the same is also true for protocols. Consider functions for a second; should we opt for global variables if we need more than one input variable? It "reduces coupling" because when it is called you don't need to know anything about the function or the input variables. I feel that many people would disagree with using functions like this.
    I will say however, that the points made from 20:59 are good use cases for protocols, and are the most compelling reasons I've heard for using them

    • @Forseti2
      @Forseti2 Před 2 lety +4

      Exactly my thoughts!

    • @ArjanCodes
      @ArjanCodes  Před 2 lety +11

      Good points!

    • @sebastianrodriguezcolina634
      @sebastianrodriguezcolina634 Před 2 lety +10

      I strongly disagree with (1), the programmer doesn't need to remember the interface, it is done by the type checker. With (2) I disagree just a bit, because you could use functools.partial and closures to remove the need for global variables.

    • @Forseti2
      @Forseti2 Před 2 lety +15

      @@sebastianrodriguezcolina634 yop, the type checker will do its job, but imagine you'll work in team of several people (some will quit the job, some new will arrive). When using ABCs it's always clear what "interface" the class implements. When using Protocol it's not so clear at first glance. The type checker or python interpreter gaves you hint eventually, but otherwise you must keep track of the interface implementations somehow (in your head when working a alone, in some shared documentation when working in the team)

    • @RichardVodden1
      @RichardVodden1 Před 2 lety +30

      I think of Protocols and ABCs as changing the ownership of the definition. ABCs are owned by the implementation, the person creating the class has to know, at the time the class is created, that they want to implement that ABC - it reduces the complexity of implementing consumers as you can be quite rigid in your ABC.
      A Protocol on the other hand is a declaration by the consumer of what they're able to consume. A Printer class may be able to consume any object which has a `print` method which returns an `str`, and therefore it defines a `Printable` protocol. The authors of the classes which the Print class consumes didn't have to realise that they were implementing the protocol.
      In both cases the method implementation has to do the right thing, and no typing mechanism is going to help assert functionality beyond the correct parameter and return types.

  • @rungxanh2901
    @rungxanh2901 Před 2 lety

    Thank you very much Aarjan! This is something college never teaches me 🤩

  • @SeanCallahan52
    @SeanCallahan52 Před 2 lety

    If your videos are anything like your code irl, it must be thumbs up.

  • @rdean150
    @rdean150 Před 2 lety +3

    Is there a way to declare that your class satisfies a Protocol, for the sake of future developer groking the design? I guess it would require an import of the Protocol class / schema. I guess that may just be where naming convention or documentation comes into play?

  • @jaortizco
    @jaortizco Před rokem

    Great content, Arjan. I'm learning a lot from your videos. I'd like to ask a question though. What should I do if I want to support different device objects from different external libraries? Let's say, for example, that they all implement a connection method but with different names, like "connection()" or "connect_to()".

  • @JoaoSantos-lv4rc
    @JoaoSantos-lv4rc Před 2 lety

    i have to admit i hadn't noticed the letterboard.. i'm sorry! love your content. it's really helped me stay motivated. And helped my coding, details and structre. thank you so much.

  • @andydudley6085
    @andydudley6085 Před 2 lety

    It's nice to see your vim usage getting better over time. Should be able to `da(` without actually having the paren selected, btw. Then you could hit `.` to repeat the command. And if you used / to find the open parent, you could then `;.;.;.;.` to repeatedly find and delete the class inheritance syntax.

  • @andrewglick6279
    @andrewglick6279 Před 2 lety +3

    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.

    • @Naej7
      @Naej7 Před rokem

      I wanted to write the same thing

  • @larsblume6670
    @larsblume6670 Před rokem

    Hi Arjan, when you uncomment line 8-9 in 2021-protocol-vs-abc/protocol/iot/devices.py, i.e. the disconnect definition, main.py still runs just fine. I suppose that's because disconnect is actually never used as part of main.py. However, I would still have expected Python to check that a Device adheres to the whole interface/protocol and not just some of it.
    For example, as of now, someone might come up with new devices that don't support the disconnect method and everything runs just fine. But then you decide to actually start using the disconnect method in main.py and things suddenly start to fail.
    Do you know why the protocol isn't enforced absolutely? Is there a way to make it more strict?

  • @personal1872
    @personal1872 Před 4 měsíci +1

    i have interface created in python using protocol but when i click to any method in vs code it does not open main method but it opens method in protocol / interface class, how can i click to open main implementation instead of interface ?

  • @ponysmallhorse
    @ponysmallhorse Před 2 lety

    So, Protocols is "Golang" interfaces principles ported to python? Am i getting this correctly?

  • @carlwestman9343
    @carlwestman9343 Před 2 lety

    Nice videos! What was the shortcut called which you used to directly remove the inheritance but not the : at around 12:00? 😉

  • @tir0__
    @tir0__ Před rokem

    What an amazing way of explanation

    • @ArjanCodes
      @ArjanCodes  Před rokem

      Thanks so much, glad you liked it!

  • @Hubert4515
    @Hubert4515 Před 2 lety +1

    thanks, i've been using these ones a lot lately!

  • @TJ-hs1qm
    @TJ-hs1qm Před měsícem

    Protocols are mirrored by Type Classes in functionsl programing
    Type classes are a powerful feature in functional programming that can help solve the expression problem of adding new types to which existing operations apply.
    In functional programming, the expression problem refers to the challenge of adding new functionality to existing code without modifying that code. This is particularly difficult when dealing with types, as adding a new type often requires modifying existing code to support it.
    Type classes provide a solution to this problem by allowing you to define a set of operations that can be applied to any type that implements the type class. This means that you can add new types to your code without modifying
    existing code, as long as those types implement the required operations.
    For example, let's say you have a type class called `Printable` that defines a single operation called `print`. Any type that implements the `Printable` type class can be printed using the `print` operation. Now, if you want to
    add a new type to your code that can be printed, you simply need to implement the `Printable` type class for that type. You don't need to modify any existing code that uses the `print` operation.

  • @krissn8111
    @krissn8111 Před rokem

    Great video. But i have a question about HueLight as protocol how is it different from any other class? I wonder if the inheritance from Device was correct if we do not expect the abstractmethods from Device to be mandatory for it.

  • @this-is-bioman
    @this-is-bioman Před rokem

    This is an excellent example! Without foos and bars 🤩

  • @courage396
    @courage396 Před 18 dny

    Great tutorial, quick question what font are you using on your IDE

  • @engdoretto
    @engdoretto Před 2 lety

    Thanks for the awesome explanation!

  • @stokesarisnet
    @stokesarisnet Před 7 měsíci

    All other issues aside, are there any performance issues between the two methods. Are the method arguments checked each time the methods are called? Thanks

  • @a1g2r3c4
    @a1g2r3c4 Před rokem

    Great explanation, you saved the day

    • @ArjanCodes
      @ArjanCodes  Před rokem

      Thank you Alejando, glad you liked the video!

  • @haabi1521
    @haabi1521 Před 2 měsíci

    In the protocol code, if I implement the device class as a normal colon 'class Device:' instead of 'class Device(protocol)'. The code can still run without any issue. Besides the IDE don't do static typing check before running. Then why we use the 'from typing import Protocol' library?

  • @johnanih56
    @johnanih56 Před 2 lety

    please how did you do the automatic import with VSCode?

  • @Antuan2911
    @Antuan2911 Před rokem

    Hi Arjan, this is an amazing useful video for beginners like me. Thank you!!!
    May I ask a silly question. A device class must have exactly the same methods
    of the Device(Protocol) class? Or just must have at least the methods protocol describes?
    I mean, can a device class has more methods than protocol needs? Thank you in advance!

  • @danilob2b2
    @danilob2b2 Před 2 lety +2

    Arjan... I really enjoy your videos. Thank you for sharing your knowledge! Would you consider doing a video about Mixins? I've seen it is largely used in Django framework, and I would like to know more about best practices about Mixins.

  • @banatibor83
    @banatibor83 Před rokem +1

    I took me a couple of minutes but I got it. Protocols are like interfaces in Java. Except in Java you have to explicitly implement an interface on an object. In python if the class has certain methods it can fulfill a protocol aka implements an interface but nothing tells the poor developer that a class actually realizes a protocol. It looks like a bunch of unrelated objects which somehow work together. The correct way would be IMO in this example to define two ABCs, Device and DiagnosticSource and a specific device should inherit from both. That way the connection would remain clear between the classes yet anything could inherit from one or the other. As I see with Protocol the code could be simpler at first glance but in reality it become more complicated and much more harder to read.
    Other problem is if a class has a certain method it fulfills a protocol when that class is never meant to do that. In the example, lets say a message queue adapter easily can pass as a device cause it probably has connect, disconnect and send_message methods.
    Protocol is a shady stuff!

  • @joningram
    @joningram Před 2 lety +1

    Interesting video - Protocols seem like a good way to formalise duck typing and effectively introduce interfaces into Python by the back door. It might even get me using typing more!
    The only thing I don't like about them is the ... notation - this joins things like dataclasses (when is something a class variable and when is it an instance variable?) and properties in stretching the syntax of classes in ways that get hard to explain to beginners. I've even read the Protocol PEP before but it didn't click with me that ... was actual syntax rather than just shorthand in their examples for code they hadn't written!

    • @joningram
      @joningram Před 2 lety

      ... and after posting that I've now read several articles about ... - I didn't realise it had such a long Python history (introduced as the singleton Ellipsis in 3.0). Perhaps because I don't use numpy, which seems to be the only place it was used before typing and protocols.
      I like the anecdote that it was introduced as a constant because they thought it looked 'cute'!

  • @and4828
    @and4828 Před 2 lety

    Another very interesting video, thanks!

  • @isodoublet
    @isodoublet Před 5 měsíci

    There's nothing wrong with multiple inheritance and this is precisely the kind of situation where it's useful. The decision between structural and nominal typing should be one of interoperability: do you want classes that implement the required interface to work with your code, or would you like to keep things controlled and open access only to those that explicitly opt in? You may want different things in different cases.

  • @moneycrab
    @moneycrab Před 2 lety

    So good 😊, such clear education

  • @clauseclause6640
    @clauseclause6640 Před 2 lety

    You can achieve the same behavior with ABC just by using the register or subclasshook methods. The main downside of ABC is that you can create an instance of the abstract class, so I'm using Protocol instead, with abstractmethods and inheritance, and that works for me.

  • @bingebinge3722
    @bingebinge3722 Před rokem

    It is funny to see how strongly Python claim to be a pure OOP language, and being slow at enhancing its OOP features. Great content and great channel!

  • @fnarsiste
    @fnarsiste Před rokem

    Hello Arjan. Thank you for the quality of your videos and all the knowledge that you dissipate.
    This video is from a year ago but you look younger (I prefer you old [😎])

  • @Michael201078
    @Michael201078 Před rokem

    The best channel for Python design principles.

  • @rrwoodyt
    @rrwoodyt Před 2 lety +3

    Excellent overview of ABCs vs Protocols. I miss the white board though-- it was one of my favourite parts of your videos.

    • @ArjanCodes
      @ArjanCodes  Před 2 lety +1

      Thanks! Who knows, perhaps the letterboard makes a return in the future 😎

    • @ThePaulWilliams
      @ThePaulWilliams Před 2 lety

      @@ArjanCodes When the one-liners come easy you should slip it back in just to see if we're paying attention. :)

  • @thichquang1011
    @thichquang1011 Před 2 lety

    So are protocols basically a standardize way to write documentation inside code?

  • @ice7mayu
    @ice7mayu Před 2 lety

    Great tutorial. Thank you very much

  • @Marv_Stuff
    @Marv_Stuff Před rokem

    I watched this video now a few times and it is really great. Now I have a question relying on the Interfaces: How would I visualize the optional diagnostic Interface in the UML (for example in mermaid)? I am on my way to understand design patterns and principles but this would be good to know for me. I also ask myself how to keep track of the different protocols in large projects (in my job we have a Django application with many….many apps)? If the question is too complex to answer maybe an idea for an advanced mermaid tutorial? ❤
    Thank you for your great videos!!!

  • @adjbutler
    @adjbutler Před 2 lety

    Thank you for this video once again.

  • @danielklaffmo4506
    @danielklaffmo4506 Před 2 lety

    Hey all cool, thank you so much for teaching us more than happy to give you the views, main focus is programming so hey thank you Arjaan I love the Netherlands btw tiptop thumbs up from a Norwegian

    • @ArjanCodes
      @ArjanCodes  Před 2 lety

      Hi Daniel, thank you and glad you like the videos! Haven’t been to Norway, but it’s a place I’d love to visit one day.

  • @hansenmarc
    @hansenmarc Před rokem

    Great stuff! Protocol seems like a nice match for using mixins. I’d love to hear your thoughts on the proper use of the mixin design pattern (for example, in developing scimitar-learn transformers or estimators).

    • @matthiasschuster9505
      @matthiasschuster9505 Před rokem +1

      He says not to use Mixins at all
      You can see this at the end of one of his videos on dataclasses
      They actually break slots on dataclasses

    • @hansenmarc
      @hansenmarc Před rokem

      @@matthiasschuster9505 Thanks! That’s very interesting. The scikit-learn library makes heavy use of mixins. I’ll have to watch the video you mentioned: czcams.com/video/Fot3_9eDmOs/video.html

  • @fernandocorenstein6531

    Best as always. Super Pro

    • @ArjanCodes
      @ArjanCodes  Před rokem +1

      Thanks so much Fernando, glad you liked it!

  • @joshdotmp4
    @joshdotmp4 Před 2 lety +2

    Love your videos, this clarified a lot of things I didn't understand about protocols. They seem to be great for splitting up coupling and being sure each part of the program only knows exactly what it needs. I have a question, though: Do protocols provide things other than type hinting? Can they raise errors or prevent vulnerabilities in other ways? I was surprised that Python didn't raise an error when you run register_device, for instance, until it actually ran into that missing connect method. Though the type hinting is very helpful in an IDE. Thanks!

    • @isodoublet
      @isodoublet Před 5 měsíci

      Type hints are glorified comments, the interpreter won't check any of them.

  • @lixzhou1140
    @lixzhou1140 Před 2 lety

    What's a correct way to specify a multi-protocol constrained parameter?

  • @Fine_Mouche
    @Fine_Mouche Před rokem

    Does Protocols are not "made"(not the main purpose) to be imported in others program files/modules/classes like we do with ABC ?

  • @oleholeynikov8659
    @oleholeynikov8659 Před 6 měsíci

    Thanks, great video! What about Sphinx dealing with Protocol?

  • @omerorhan80
    @omerorhan80 Před 2 lety

    Can you do a DDD and event sourcing example with KAFKA in python please? There is not much samples around with python.

  • @DrDeuteron
    @DrDeuteron Před rokem

    4:00 why isn't that function a Device method, since it's only parameter is a device instance?

  • @ari_archer
    @ari_archer Před rokem

    This one's really helpful

    • @ArjanCodes
      @ArjanCodes  Před rokem

      Thanks Ari, Glad that the content it helpful

  • @DS-tj2tu
    @DS-tj2tu Před 2 lety

    Thank you

  • @preadaptation
    @preadaptation Před 6 měsíci

    Thanks

    • @ArjanCodes
      @ArjanCodes  Před 6 měsíci

      Thank you for the support! Glad you enjoyed the content :)

  • @zacky7862
    @zacky7862 Před 2 lety

    Finally this is what I've been waiting to fully understand the use and importance of abstract and protocol.
    What error highlighting you are using? I'm using pylint but it's not showing like that specially on unused imports

    • @ArjanCodes
      @ArjanCodes  Před 2 lety +2

      I’m using the Python extension in VS Code (Pylance). To get the type checking messages, make sure that typeCheckingMode in your settings is set to ‘strict’. See also: code.visualstudio.com/docs/python/settings-reference.

    • @zacky7862
      @zacky7862 Před 2 lety

      @@ArjanCodes Oh thank you so much.

    • @zacky7862
      @zacky7862 Před 2 lety

      @@ArjanCodes Thank you it's now working.

  • @MrDivar
    @MrDivar Před 11 měsíci

    Hi @arjanCodes, I'm curious to know what course you provide includes the amazing video, Protocol Or ABC In Python - When to use which one?, I just watched above. Is this part of "The Software Designer Mindset" course?

    • @ArjanCodes
      @ArjanCodes  Před 11 měsíci

      Hi! it's covered in The Software Designer Mindset. :)