What are "Protocols" In Python? (Tutorial 2023)

Поделиться
HTML-код
  • Опубликовано: 28 янв 2025

Комментарии • 71

  • @senayan6823
    @senayan6823 Год назад +29

    Thanks for the presentation! What is the advantage of this technique compared to using the ABC superclass with @abstractmethod decorators?

    • @AeroEng123
      @AeroEng123 Год назад +3

      I don't see a benefit to this over abstract base classes. This warns you in editor but ABC will raise an exception if you don't implement the required methods, etc. So this just looks like a worse version of ABC.

    • @Jason-b9t
      @Jason-b9t Год назад +13

      ​@@AeroEng123 The biggest advantage is that there is no need to deal with a bunch of inheritance relationships when using Protocol. If you only use ABC, your code will soon become as complicated as JAVA.
      Because Protocol only uses method/property signatures, it does not need to deal with inheritance issues.
      P.S.: If you need unimplemented warnings, you can explicitly inherit from Protocol (e.g.: class Book(Printable)). This way pyright can understand the relationship and warn you, and that no inheritance relationship will actually occur on Book (it will be an implementation relationship).

    • @Indently
      @Indently  Год назад +4

      I really enjoy readying these kind of comments, I wish there were more of these around!

    • @vorpal22
      @vorpal22 Год назад +2

      @@Jason-b9t I'm not sure how inheritance relationships make the code more complicated. There should be an indication that there is a relationship between a Protocol and something that implements the Protocol in case you change the Protocol at some point,.
      Java isn't really all that complicated. To what inheritance issues are you referring?
      Even if you chose to implement a Protocol like Printable, I'm not sure why you wouldn't explicitly inherit from it.

    • @vorpal22
      @vorpal22 Год назад

      @@Jason-b9t I mean, it seems this just is a more formal implementation of duck typing, which is how Python works in the first place by default.

  • @vorpal22
    @vorpal22 Год назад +20

    What is the advantage of using Protocol over a Printable ABC and then inheriting?
    I didn't formerly know about Protocol, so thanks for teaching me something new, but I'm curious what the advantage is over the approach I would typically use.

    • @KashyapMaheshwari
      @KashyapMaheshwari Год назад

      One of the benefits I see is inheritance. Using ABCs, you'd have to inherit the ABC which adds to runtime overhead. Using protocols, we avoid that since they are 'inherited' purely by its structure

    • @vorpal22
      @vorpal22 Год назад +1

      ​@@KashyapMaheshwariI guess when people start talking about runtime overhead in Python, I zone out. Obviously, there are ways to write Python code to be faster, but if you are concerned about something like runtime overhead, you probably aren't picking the right tool for the job if you go with Python: it seems like another programming language might be a better choice.

    • @knolljo
      @knolljo 11 месяцев назад

      It’s more like a Trait. If i want to have a function which takes something that can send() and recv() data i can pass in a socket, websocket or any other type that implements those, even my own types, implementing an abc on those types, from “outside” packages, is not as easy

    • @vorpal22
      @vorpal22 11 месяцев назад

      @@knolljoIt feels loosey-goosey to me... I'm not sure why you wouldn't make it simply implement an interface, or even implement a typeclass. It's like, "I'm an XYZ Protocol because I have the members of XYZ even though this isn't officially stated anywhere."
      I'm not quite sure how it's different from pure duck typing, or C++ SFINAE.

    • @knolljo
      @knolljo 11 месяцев назад +1

      @@vorpal22 absolutely, python typing is wonky

  • @simonhuang2013
    @simonhuang2013 Год назад +22

    Are you going to cover the comparison between ABC and protocol in future videos ? In my opinion, they do pretty much the same thing except one is checked before runtime, the other is checked during runtime

    • @DrDeuteron
      @DrDeuteron Год назад +4

      I'd go ABC. This seems like it's a way to interact with your IDE.

    • @rupen42
      @rupen42 Год назад +2

      @DrDeuteron You're right that protocols have no effect unless you are using a type checker (eg mypy) or an IDE that uses that under the hood. But that doesn't mean they aren't useful.

    • @BradleyBell83
      @BradleyBell83 11 месяцев назад +1

      I like ABC better just for readability. If a class inherits from an ABC, you know if needs to implement all methods of that interface. Duck typing just seems too ambiguous for me.

    • @adolfomartin5456
      @adolfomartin5456 9 месяцев назад

      @@DrDeuteron It is not that. Language program features and IDE are not related.

    • @DrDeuteron
      @DrDeuteron 9 месяцев назад

      @@adolfomartin5456 not since type hints started. When I see:
      N_INT: int = 3 # int(eger) equal to three
      or
      def __str__(self: Self) -> str:
      ppl justify it by saying "It lets my IDE know"...so IDE and language may overlap for you, but for a large portion of the python community, they do.

  • @AlexCernat
    @AlexCernat Год назад +2

    so iiac it's no "implements" keyword and no explicit relation between interface and actual class, but the class must implement in code all required "requirements" from interface (protocol)

  • @chriskeo392
    @chriskeo392 Год назад +3

    The first minute was enlightening but then you made the fruit eat itself 😂
    Finished the video
    Wow, you're an incredible teacher.
    Would love this approach on ABC
    And the MVC architecture (framework agnostic)

  • @dragweb7725
    @dragweb7725 Год назад +4

    we are agreed that here the Book and Magazine classes don't inherit from Printable right ? that's the main point of the thing in my opinion, as like this we shouldn't deal with inheritance flaws like funky behavior when using super() or things like this

    • @erikkonstas
      @erikkonstas Год назад +1

      Yes, for example Java doesn't let you inherit from multiple classes, only from multiple interfaces (so as to avoid "diamond patterns" for example), so yes you don't use class inheritance.

    • @Indently
      @Indently  Год назад +2

      Yeah none of them inherit. Sorry if I used the term inherit in this video in places that I shouldn't have. It might have made things more confusing than they had to be.

    • @dragweb7725
      @dragweb7725 Год назад +1

      @@Indently i don't think you did that, i just made a parallel between the two things as they are both "connecting" classes together

    • @robinpipslayertekprofitsfa2644
      @robinpipslayertekprofitsfa2644 11 месяцев назад

      And what most people may not realise, this is a very advanced technique!
      You would not normally create the "Book/Magazine" class on the same module. You would rather put all your templates on this module then import to use where.required(object).
      Thus it's use case can be validated by requirements.

  • @Firetech2004
    @Firetech2004 Год назад

    Hey, just wanted to drop a thank you ❤ Have been watching your videos lately and they are helping me master python.

  • @360withpaul
    @360withpaul Год назад

    Thanks for sharing, very nice video! Keep it up 🔥

  • @kunalsoni7681
    @kunalsoni7681 Год назад

    This is nice to do with our code to make the codebase more robust ❤‍🔥

  • @DeltaXML_Ltd
    @DeltaXML_Ltd Год назад

    Fantastic video!

  • @Eltoncbraz
    @Eltoncbraz Год назад

    That's very interesting. Can we simulate this behavior using an abstract class? What are the drawbacks and advantages of these different approaches? Show us how VSCode can provide hints to the user when implementing the subclasses.

  • @link_safe
    @link_safe Год назад +1

    what extension do you use that shows how much usage a object has been used (eg. 1 usage, 2 usages, ...)?

    • @Indently
      @Indently  Год назад +1

      PyCharm does that since the latest update now

    • @Indently
      @Indently  Год назад +2

      I never choose anything 🤣

    • @link_safe
      @link_safe Год назад

      @@Indently Ah, awesome (wish VSCode had that feature too 😔)

    • @link_safe
      @link_safe Год назад

      @@Indently I see 😂

    • @erikkonstas
      @erikkonstas Год назад +1

      @@link_safe TBF that number isn't really important, you can right click and "Go to References" to see *what* uses it exactly.

  • @alexstone691
    @alexstone691 Год назад

    Im guessing this just more lightweight way to use ABC that does not have runtime penalty? Even though i do not know if there is much penalty anyways

  • @tfr
    @tfr Год назад +1

    pretty cool and may only help in the developer experience. may be suitable for a module or something but fairly useless in standalone programs. great video as always though :)

  • @Pawlo370
    @Pawlo370 Год назад

    2:22 ó? you have polish keyboard?

  • @miguelvasquez9849
    @miguelvasquez9849 Год назад +1

    For some reason, VSC is not generating warnings for this example.

    • @codewithpranoy
      @codewithpranoy Год назад +3

      Use static type checkers like pyright or ruff

    • @erikkonstas
      @erikkonstas Год назад +2

      You have to enable type checking in Code (it's at the bottom-right, where it says "Python" it should have a "{}" next to it).

  • @jamesmiller5984
    @jamesmiller5984 Год назад +1

    I might use this because when I use polymorphism I always mess something up

  • @erichstocker8358
    @erichstocker8358 11 месяцев назад

    If Banana inherits from Fruit then it would have the parent eat available to it. Not sure why an interface would be necessary there

  • @rooftop1510
    @rooftop1510 Год назад

    is this similar to abstract base class?

    • @Jason-b9t
      @Jason-b9t Год назад +1

      This is different from the behavior of the abstract base class. If you use an abstract base class, you will create an inheritance relationship, and isinstance(book, AbcPrintable) will return True.
      Protocols is a static duck class provided to pyright for checking method/property signatures. There is no inheritance relationship between Protocol and the corresponding class, isinstance(book, Printable) will throw TypeError: Instance and class checks can only be used with @runtime_checkable protocols, and pyright will warn you about it.

  • @isabellareyesrodriguez210
    @isabellareyesrodriguez210 Год назад

    Is that an abstraction?

    • @DecimasoN
      @DecimasoN Год назад

      It's similar to abstract ABC (abstractmethod) but it will error at a different stage. e.g. Instantiation vs method call

  • @rishiraj2548
    @rishiraj2548 Год назад +1

    Good day greetings

  • @mista_ia
    @mista_ia Год назад

    You did not make a tutorial about ABCs yet !!!

  • @LuvxJacqu4li8e
    @LuvxJacqu4li8e Год назад

    Hmmm...

  • @codefields
    @codefields 6 месяцев назад

    I don't know, the whole object model from python it's so poorly designed, the lack of real encapsulation, proper decent type check at runtime, decent interfaces.... makes me laugh. Python will be the future PHP

  • @alexgghlebg5375
    @alexgghlebg5375 Год назад

    i'm new to python, it is like an inheritance objeck ?
    Thx for the discovery, i will use it now and finaly stop using the annoying super() method to inheritance property and method.

    • @Indently
      @Indently  Год назад +3

      Not quite, so I wouldn't completely replace one with another, they do different things that can seem quite similar.
      The Protocol is just a "guideline" of what your other class should look like. Inheriting on the other hand will directly give you access to the methods from the parent class (through inheritence).
      That was a very dirty summary, but if you want to dive deeper, Arjan Codes did a video on Inheritence vs Protocols I think?

    • @memes_gbc674
      @memes_gbc674 Год назад

      @@Indently it is definitely hard to explain, but from what i've gathered from java you are essentially creating an object that doesn't necessarily inherit from an object but will always have a subset of methods defined. this lets you check if an object passed into a function has the implementation of "printable", the example you used in the video. this also allows the developer to know what they can or can't do with an object, so it sort of acts like self documenting code

    • @DrDeuteron
      @DrDeuteron Год назад

      super() is not annoying, it's fantastic. Read Raymond Hetinger's "python super() considered super"

  • @piwuuuv
    @piwuuuv Год назад

    I don't know english can anyone help me learn english

  • @LinuxForLife
    @LinuxForLife Год назад +1

    Could have 3 min long. A lot of talk and boilerplate ... Try to get to the point and it will be better for all of us.

    • @Indently
      @Indently  Год назад +2

      It sounds like you're too advanced for these videos, I recommend mcoding at this point. These videos won't do you any good

    • @robinpipslayertekprofitsfa2644
      @robinpipslayertekprofitsfa2644 11 месяцев назад

      ​@@IndentlyI respect You!! Most students may not grasp the concept of this video.... but it's okay 😊

  • @MichielvanderBlonk
    @MichielvanderBlonk Год назад +1

    I find this silly. Making Python look like Java for no reason. If you like Java so much then program in Java. Python's major advantage is that it is dynamically typed. None of this is necessary and just bloats your code.

    • @codingjq
      @codingjq Год назад +1

      After looking at the docs on this, I came to this video to see what the point of having this was, especially when we ABCs as well. You found the same answer as me, it's just extra.

    • @DrDeuteron
      @DrDeuteron Год назад +1

      omg, I worked a PJ led by a java coder, and it had explicit getters and setters, with the latter used after null instantiation....it was so painful. Stuff like
      constellation.getSatellite().getInstrument().getSensor().getTelemetry().getVoltages().getHeater()
      I was all @property ppl, pls.