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

แชร์
ฝัง
  • เผยแพร่เมื่อ 24 พ.ย. 2024

ความคิดเห็น • 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 ปีที่แล้ว +19

    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 9 หลายเดือนก่อน

      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 9 หลายเดือนก่อน

      @@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 9 หลายเดือนก่อน +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 10 หลายเดือนก่อน +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 8 หลายเดือนก่อน +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 7 หลายเดือนก่อน

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

    • @DrDeuteron
      @DrDeuteron 7 หลายเดือนก่อน

      @@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)

  • @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 9 หลายเดือนก่อน

      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.

  • @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)

  • @kunalsoni7681
    @kunalsoni7681 ปีที่แล้ว

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

  • @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.

  • @360withpaul
    @360withpaul ปีที่แล้ว

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

  • @Firetech2004
    @Firetech2004 ปีที่แล้ว

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

  • @DeltaXML_Ltd
    @DeltaXML_Ltd ปีที่แล้ว

    Fantastic video!

  • @jamesmiller5984
    @jamesmiller5984 ปีที่แล้ว +1

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

  • @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 :)

  • @erichstocker8358
    @erichstocker8358 8 หลายเดือนก่อน

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

  • @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.

  • @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).

  • @rishiraj2548
    @rishiraj2548 ปีที่แล้ว +1

    Good day greetings

  • @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.

  • @mista_ia
    @mista_ia ปีที่แล้ว

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

  • @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

  • @LuvxJacqu4li8e
    @LuvxJacqu4li8e ปีที่แล้ว

    Hmmm...

  • @codefields
    @codefields 4 หลายเดือนก่อน

    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

  • @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 9 หลายเดือนก่อน

      ​@@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.

  • @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"