Combining protocols with the `&` operator

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. :slight_smile:

A more general PEP for type intersections is currently being drafted [1], I don’t think it makes sense to implement protocol intersections in a separate step, even if it is easier than a more general type intersection.

In the meantime there’s this mypy plugin for Protocol intersections: typing-protocol-intersection · PyPI

  1. ↩︎


Oh, that’s really great!

I looked through this page and the GitHub issues and didn’t find anything on a first pass.

It looks like they are also proposing using A & B for defining intersections, so great timing then! :slight_smile:

Will be looking forward to developments from the PEP proposal then.