Whereas with Protocols it's gonna be ( good tutorial ): I think that is not a good example of how to write programs. What he did by having protocols I would have done by using mixins. The way that I see objects is that they have various capabilities that can be mixed in. multiple inheritance in python would have been a much better way to implement that example in my opinion. I would also say that the author of this tutorial needs to learn a thing or 2 about an inversion of control and dependency injection. The author basically sets up a straw man problem and then solves his straw man problem. He had no business creating instances of the object outside of the class itself. If he had simply called a constructor methods within the classes then the other class wouldn't have been attempting to make instances of those other classes. Answer from thedeepself on reddit.com
🌐
Python
typing.python.org › en › latest › spec › protocol.html
Protocols — typing documentation
If a class defines all attributes and methods of a protocol with types that are assignable to the types of the protocol’s attributes and methods, it is said to implement the protocol and to be assignable to the protocol. If a class is assignable to a protocol but the protocol is not included in the MRO, the class is implicitly assignable to the protocol. (Note that one can explicitly subclass a protocol and still not implement it if a protocol attribute is set to None in the subclass. See Python data model for details.)
🌐
Real Python
realpython.com › python-protocol
Python Protocols: Leveraging Structural Subtyping – Real Python
July 25, 2024 - This feature allows you to enforce a relationship between types or classes without the burden of inheritance. This relationship is known as structural subtyping or static duck typing. In this tutorial, you’ll focus on this second meaning of the term protocol. First, you’ll have a look at how Python manages types.
🌐
Sarahabd
sarahabd.com › sarah abderemane's website › til › python protocol typing
TIL: python Protocol and typing
December 18, 2024 - To conclude with, Protocols provide a way to define structural typing in Python, allowing you to create interfaces without the need for explicit inheritance. They enable type checkers to verify that objects adhere to the defined protocols, enhancing code correctness and maintainability.
🌐
Medium
medium.com › @commbigo › python-typing-protocol-c2f6a60c0ac6
Python typing — Protocol
December 28, 2023 - from typing import Protocol, TypeVar, Generic T = TypeVar("T") class Job(Protocol[T]): def run(self, info: T) -> T: print(f"run the job {info}") return info class Job1(): def run(self, info: str) -> str: print(f"run the job1 {info}") return info def run_job(job: Job): job.run("test") job1: Job[str] = Job1() run_job(job1)
🌐
Mypy
mypy.readthedocs.io › en › stable › protocols.html
Protocols and structural subtyping - mypy 1.19.1 documentation
Class Dog is a structural subtype ... latter, and with compatible types. Structural subtyping can be seen as a static equivalent of duck typing, which is well known to Python programmers. See PEP 544 for the detailed specification of protocols and structural subtyping in ...
🌐
Python
typing.python.org › en › latest › reference › protocols.html
Protocols and structural subtyping — typing documentation
Protocols can be recursive (self-referential) and mutually recursive. This is useful for declaring abstract recursive collections such as trees and linked lists: from typing import TypeVar, Optional, Protocol class TreeLike(Protocol): value: int @property def left(self) -> Optional['TreeLike']: ...
Find elsewhere
🌐
Pybites
pybit.es › articles › typing-protocol-abc-alternative
Leveraging typing.Protocol: Faster Error Detection And Beyond Inheritance – Pybites
February 9, 2024 - Unlike traditional dynamic typing, which Python is well-known for, typing.Protocol brings a layer of static type checking that allows for more explicit, readable, and robust code by defining expected behaviors and structures.
🌐
Xebia
xebia.com › home › blog › protocols in python: why you need them
Protocols In Python: Why You Need Them | Xebia
July 25, 2022 - What is the main advantage of using Python protocols? Protocols provide a flexible way to perform static type checking without requiring explicit inheritance or registration, offering the benefits of both static and dynamic typing.
🌐
Python documentation
docs.python.org › 3 › library › typing.html
typing — Support for type hints
3 weeks ago - Protocol classes decorated with runtime_checkable() (described later) act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures. Protocol classes without this decorator cannot be used as the second argument to isinstance() or issubclass(). ... In code that needs to be compatible with Python 3.11 or older, generic Protocols can be written as follows:
🌐
Reddit
reddit.com › r/python › interfaces with protocols: why not ditch abc for good?
r/Python on Reddit: Interfaces with Protocols: why not ditch ABC for good?
January 22, 2023 -

Hello, if one finds interfaces useful in Python (>=3.8) and is convinced that static type-checking is a must, then why not ditch ABC and always use Protocols? I understand that the fundamental idea of a protocol is slightly different from an interface, but in practice, I had great success replacing abc's with Protocols without regrets.

With abc you would write (https://docs.python.org/3/library/abc.html) :

from abc import ABC, abstractmethod

class Animal(ABC):
   @abstractmethod
   def eat(self, food) -> float:
       pass

Whereas with Protocols it's gonna be (good tutorial):

from typing import Protocol

class Animal(Protocol):
   def eat(self, food) -> float:
       ...

Scores in my subjective scoring system :)

CapabilityABCProtocols
Runtime checking11 (with a decorator)
Static checking with mypy11
Explicit interface (class Dog(Animal):)11
Implicit interface with duck-typing (class Dog:)0.5 (kind of with register, but it doesn't work with mypy yet)1
Default method implementation (def f(self): return 5)-1 (implementations shouldn't be in the interfaces)-1 (same, and mypy doesn't catch this)
Callback interface01
Number of code lines-1 (requires ABC inheritance and abstracmethod for every method)0 (optionalProtocol inheritance)
Total score1.54

So I do not quite see why one should ever use ABC except for legacy reasons. Other (IMHO minor) points in favour of ABC I've seen were about interactions with code editors.

Did I miss anything?

I put more detailed arguments into a Medium. There are many tutorials on using Protocols, but not many on ABC vs Protocols comparisons. I found a battle of Protocols vs Zope, but we are not using Zope, so it's not so relevant.

🌐
Mimo
mimo.org › glossary › python › protocol
Python Protocol: Syntax, Usage, and Examples
Now any class that has read() and write() methods automatically matches ReadWriter in the eyes of the type checker. Protocols became part of the standard typing module in modern Python versions.
🌐
DEV Community
dev.to › shameerchagani › what-is-a-protocol-in-python-3fl1
What is a Protocol in python? - DEV Community
July 5, 2023 - To conclude with,Protocols provide a way to define structural typing in Python, allowing you to create interfaces without the need for explicit inheritance. They enable type checkers to verify that objects adhere to the defined protocols, enhancing ...
🌐
mypy
mypy.readthedocs.io › en › latest › protocols.html
Protocols and structural subtyping - mypy 1.20.0+dev.17326d04fc86f03084c9167a3b75b9fab311b686 documentation
Class Dog is a structural subtype ... latter, and with compatible types. Structural subtyping can be seen as a static equivalent of duck typing, which is well known to Python programmers. See PEP 544 for the detailed specification of protocols and structural subtyping in ...
🌐
Python
peps.python.org › pep-0544
PEP 544 – Protocols: Structural subtyping (static duck typing) | peps.python.org
Currently, PEP 484 and the typing module [typing] define abstract base classes for several common Python protocols such as Iterable and Sized. The problem with them is that a class has to be explicitly marked to support them, which is unpythonic and unlike what one would normally do in idiomatic dynamically typed Python code.
🌐
Turingtaco
turingtaco.com › static-duck-typing-with-pythons-protocols
Static Duck Typing With Python’s Protocols
December 7, 2024 - The term Duck Typing has been primarily used in dynamically typed languages; when combined with compile time verification, it is usually named Structural Typing. Some languages, like Go or TypeScript, adopt this approach over the nominal one, ...
🌐
Hashnode
fronkan.hashnode.dev › a-first-look-at-python-protocols-pep-544
A First Look at Python Protocols (PEP 544) - Fredrik Sjöstrand
October 5, 2020 - The title of the PEP says static ... has to fulfill, and if does it is said to be an instance of the protocol. Protocols are just checked by type-checking tools and aren't enforced at run-time....
🌐
Python.org
discuss.python.org › typing
Compatibility of protocol class object with `type[T]` and `type[Any]` - Typing - Discussions on Python.org
March 14, 2024 - The typing spec is clear that "variables and parameters annotated with type[Proto] accept only concrete (non-protocol) subtypes of Proto. This means the following code should result in a type error. class Proto(Protocol): x: int def func1(v: type[Proto]): pass # Type error: Only concrete class can be given where "type[Proto]" is expected func1(Proto) And indeed, mypy and pyright both generate a type error here.
🌐
Adam Johnson
adamj.eu › tech › 2021 › 05 › 18 › python-type-hints-duck-typing-with-protocol
Python type hints: duck typing with Protocol - Adam Johnson
A protocol type contains a set of typed methods and variables. If an object has those methods and variables, it will match the protocol type. typing.Protocol was added in Python 3.8. On prior versions of Python, you can use typing_extension...
🌐
Andrewbrookins
andrewbrookins.com › technology › building-implicit-interfaces-in-python-with-protocol-classes
Building Implicit Interfaces in Python with Protocol Classes – Andrew Brookins
July 5, 2020 - This feature lets you build interfaces and check that objects satisfy them implicitly, much like you can in Go. You might call this static duck-typing. Intrigued? Let’s check out how protocol classes work by writing some code.
🌐
Auth0
auth0.com › blog › protocol-types-in-python
Protocol Types in Python 3.8
June 23, 2021 - While the concept is the same as Clojure, Python does not need explicit protocol declaration. If a type has the methods specified in the protocol, then it implements the protocol.