Would it be of interest to anyone else to be able to combine Protocols with the & operator?
This could help address typing issues once a project embraces dependency inversion and starts using small protocols to define interfaces across the entire project.
When defining, for example, a Protocol that implements __len__ and __getitem__, one must currently define your own protocol or inherit from other protocols:
from typing import Protocol, TypeVar
T_co = TypeVar("T_co", covariant=True)
class SizedCollection(Generic[T_co], Protocol):
def __len__(self) -> int: ...
def __getitem__(self, __key) -> T_co: ...
from typing import Sized, Protocol, Generic, TypeVar
T_co = TypeVar("T_co", covariant=True)
class SizedCollection(Sized, Generic[T_co], Protocol):
def __getitem__(self, __key) -> T_co: ...
This idea would enable new protocols to be defined as:
from typing import Sized, GetItemProtocol
SizedCollection = Sized & GetItemProtocol
def func(obj: Sized & GetItemProtocol):
...
The type checker would then know that SizedCollection implements the interface defined in Sized AND the hypothetical GetItemProtocol, with the order of operands determining inheritance rules.
It could play well with the new generic syntax:
type SizedCollection[T] = Sized[T] & GetItemProtocol[T]
It also plays well in contrast with the current use of the union | operator to define types, and seems intuitive based on the rest of the typing syntax in my view.
Thoughts? Would love to hear the community’s opinions. ![]()