Protocols don't allow that, because it breaks subtype transitivity. See PEP 544.

If you have the following two classes:

class A:
    def method(self, arg: int):
        pass

class B(A):
    def method(self, arg: object):
        pass

then B is a valid subclass of A, because B.method can accept any arguments A.method can. However, if you could introduce the following protocol:

T = typing.TypeVar('T')

class Proto(typing.Protocol[T]):
    def method(self, arg: T):
        pass

then A would satisfy Proto[int], but B would not, due to the invariance of T.

Answer from user2357112 on Stack Overflow
🌐
Python
typing.python.org › en › latest › spec › protocol.html
Protocols — typing documentation
A protocol P1 is assignable to another protocol P2 if P1 defines all protocol members of P2 with assignable types. Generic protocol types follow the same rules of variance as non-protocol types. Protocol types can be used in all contexts where any other types can be used, such as in unions, ...
Discussions

Issue with generic Protocol
There was an error while loading. Please reload this page · and Pyright see it as a valid code so I think it should be seen as valid by mypy More on github.com
🌐 github.com
2
February 15, 2022
Variance of arguments for Generic ABC vs Generic Protocol
I am trying to define a Generic base class, but see different type checking behavior when I inherit from abc.ABC versus Protocol. I am trying to figure out if it is really a difference of variance ... More on github.com
🌐 github.com
1
1
July 9, 2024
@typing.protocol decorator to create a class of type Protocol - Ideas - Discussions on Python.org
Instead of having typing.Protocol, which we inherit to define a Protocol class, we could have a global @protocol decorator that declares a class as a Protocol. And the class that adheres to that Protocol should be decorated with a decorator having the name of the Protocol class it adheres to. More on discuss.python.org
🌐 discuss.python.org
0
October 5, 2022
classmethod's in generic protocols with self-types
Are you reporting a bug, or opening a feature request? A potential bug So, I've posted a corresponding question on StackOverflow, but it hasn't gotten much traction. Here is my basic situat... More on github.com
🌐 github.com
6
November 6, 2018
🌐
Real Python
realpython.com › python-protocol
Python Protocols: Leveraging Structural Subtyping – Real Python
July 25, 2024 - Protocol classes can be generic. To create a generic protocol, you can use the typing.TypeVar class.
🌐
Python
peps.python.org › pep-0544
PEP 544 – Protocols: Structural subtyping (static duck typing) | peps.python.org
March 5, 2017 - Generic protocol types follow the same rules of variance as non-protocol types. Protocol types can be used in all contexts where any other types can be used, such as in Union, ClassVar, type variables bounds, etc.
🌐
Python
typing.python.org › en › latest › reference › generics.html
Generics — typing documentation
Protocols can also be generic (see also Protocols and structural subtyping). Several predefined protocols are generic, such as Iterable[T], and you can define additional generic protocols. Generic protocols mostly follow the normal rules for generic classes.
🌐
mypy
mypy.readthedocs.io › en › latest › generics.html
Generics - mypy 1.20.0+dev.acfef9c84da69805f740e67b108910888d66f7ab documentation
Mypy supports generic protocols (see also Protocols and structural subtyping). Several predefined protocols are generic, such as Iterable[T], and you can define additional generic protocols. Generic protocols mostly follow the normal rules for generic classes. Example (Python 3.12 syntax):
🌐
Turingtaco
turingtaco.com › protocols-default-methods-inheritance-and-more
Protocols: Default Methods, Inheritance, and More
December 7, 2024 - This functionality is beneficial for delivering common or generic implementations that can serve as a fallback or standard behavior. This aspect of Protocols resembles Scala or Rust's traits. Traits allow the bundling of method definitions with an interface. While the Protocol's primary benefit is develop-time-checked structural typing, adding default implementations brings a flavor of trait-like functionality to the language. It's important to note that classes in Python do not need to be directly inherited from a Protocol to be considered as implementing that Protocol.
Find elsewhere
🌐
Medium
medium.com › @commbigo › python-typing-protocol-c2f6a60c0ac6
Python typing — Protocol
December 28, 2023 - Protocol can be applied to all members within the class, encompassing variables, functions, and abstract methods. Another noteworthy topic is the “Generic Protocol.” Using the above code as an example, consider the scenario where we have input for the run function, and we want to make it compatible with both int and str.
🌐
Mypy
mypy.readthedocs.io › en › stable › protocols.html
Protocols and structural subtyping - mypy 1.19.1 documentation
In Python 3.9 and later, the aliases in typing don’t provide any extra functionality. You can define your own protocol class by inheriting the special Protocol class:
🌐
Mypy
mypy.readthedocs.io › en › stable › generics.html
Generics - mypy 1.19.1 documentation
Mypy supports generic protocols (see also Protocols and structural subtyping). Several predefined protocols are generic, such as Iterable[T], and you can define additional generic protocols. Generic protocols mostly follow the normal rules for generic classes. Example (Python 3.12 syntax):
🌐
GitHub
github.com › python › mypy › issues › 12183
Issue with generic Protocol · Issue #12183 · python/mypy
February 15, 2022 - from dataclasses import dataclass from typing import Generic, Protocol, TypeVar import pandas as pd _DataFrameBound = TypeVar("_DataFrameBound", bound=pd.DataFrame, covariant=True) class _Method(Protocol[_DataFrameBound]): def __call__(self, ...
Author   bloussou
🌐
GitHub
github.com › python › typing › discussions › 1739
Generic Protocol with method taking instance of Protocol (e.g. Functor) · python/typing · Discussion #1739
May 17, 2024 - class Applicative(Functor[A], Protocol[A]): @staticmethod def pure(x: Any) -> Applicative[A]: ... @staticmethod def ap(f: Applicative[Callable[[A], B]], x: Applicative[A]) -> Applicative[B]: ... class Monad(Applicative[A], Protocol[A]): @staticmethod def bind(x: Monad[A], f: Callable[[A], Monad[B]]) -> Monad[B]: ... @dataclass class Io(Generic[A]): action: Callable[[], A] @staticmethod def fmap(f: Callable[[A], B], x: Io[A]) -> Io[B]: return Io(lambda: f(x.action())) @staticmethod def pure(x: A) -> Io[A]: return Io(lambda: x) @staticmethod def ap(f: Io[Callable[[A], B]], x: Io[A]) -> Io[B]: return Io(lambda: f.action()(x.action())) @staticmethod def bind(x: Io[A], f: Callable[[A], Io[B]]) -> Io[B]: return Io(lambda: f(x.action()).action()) def taking_monad(x: Monad[int]) -> bool: return True taking_monad(Io(lambda: 1))
Author   python
🌐
Medium
medium.com › @shane-zhang › python-adventure-demystifying-generic-types-e7a1b64b75ed
Python Adventure: Demystifying Generic Types | by Shane Zhang | Medium
November 21, 2024 - A protocol defines what methods and behaviors a class must have, but it doesn’t need to be explicitly inherited. As long as the object follows the “rules” (method signatures), it is treated as a valid implementation, even if it’s not a subclass. This is duck typing in action! My first impression of TypeVar and Generic in Python was: why are we using two things for one type?!
🌐
GitHub
github.com › python › typing › discussions › 1793
Variance of arguments for Generic ABC vs Generic Protocol · python/typing · Discussion #1793
July 9, 2024 - import abc from typing import Generic, Protocol, TypedDict, TypeVar class BaseResult(TypedDict): """ Result """ R = TypeVar("R", bound=BaseResult) R_contra = TypeVar("R_contra", bound=BaseResult, contravariant=True) class BadProtocolResultWriter(Protocol[R]): """ Type variable "R" used in generic protocol "ProtocolResultWriter" should be contravariant (reportInvalidTypeVarUse) main.py:16: error: Invariant type variable "R" used in protocol where contravariant one is expected [misc] """ @abc.abstractmethod def write( self, result: R, ) -> None: """ Write to destination """ class ABCResultWriter(abc.ABC, Generic[R]): """ This type checks just fine, but what is different compared to the Protocol equivalent?
Author   python
🌐
Auth0
auth0.com › blog › protocol-types-in-python
Protocol Types in Python 3.8
June 23, 2021 - In this article, we're going to ... typing, and other idiomatic patterns in Python. Protocol is a very generic word, both in regular language as well as in Computer Science....
🌐
Python documentation
docs.python.org › 3 › library › typing.html
typing — Support for type hints
1 month 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:
🌐
Xebia
xebia.com › home › blog › protocols in python: why you need them
Protocols In Python: Why You Need Them | Xebia
July 25, 2022 - The protocol class implementation defines rules and guidelines for implementing protocol methods within a class, including the use of variable annotations. Python Protocol class variables are defined within the class body of a protocol, and there is a distinction between protocol class variables and protocol instance variables.
🌐
Python.org
discuss.python.org › ideas
@typing.protocol decorator to create a class of type Protocol - Ideas - Discussions on Python.org
October 5, 2022 - Instead of having typing.Protocol, which we inherit to define a Protocol class, we could have a global @protocol decorator that declares a class as a Protocol. And the class that adheres to that Protocol should be decorated with a decorator having the name of the Protocol class it adheres to.
🌐
GitHub
github.com › python › mypy › issues › 5872
classmethod's in generic protocols with self-types · Issue #5872 · python/mypy
November 6, 2018 - from dataclasses import dataclass from typing import Union, ClassVar, TypeVar, Generic, Type from typing_extensions import Protocol _P = TypeVar('_P', bound='PType') class PType(Protocol): @classmethod def maximum_type_value(cls: Type[_P]) -> _P: ... @classmethod def minimum_type_value(cls: Type[_P]) -> _P: ...
Author   juanarrivillaga
🌐
GitHub
github.com › python › mypy › issues › 6801
Generic Protocol breaks mypy when attrs class · Issue #6801 · python/mypy
May 8, 2019 - test.py:20:1: error: Invariant type variable 'T' used in protocol where contravariant one is expected test.py:24:5: error: Function is missing a return type annotation · What are the versions of mypy and Python you are using? Do you see the same issue after installing mypy from Git master?
Published   May 08, 2019