'Extending Python ABCs with a protocol

I'd like to create a new typing protocol that extends some common base classes (e.g., Iterable) with additional attributes. For example

from typing import Iterable, Protocol

class IterableWithMethod(Iterable, Protocol):
    def method(self) -> None: pass


class ImplementsProtocol():
    def __iter__(self):
        ...
    
    def method(self):
        ...

def operatesOnProtocol(in: IterableWithMethod):
    ...

However, protocols cannot subclass normal classes. Is there a standard way to do this? Do protocol versions of the ABCs need to be added to the standard library?



Solution 1:[1]

Given that mypy lists many of the abstract types exported by typing as "predefined protocols" and "Python protocols such as Iterable and Sized" are explicitly mentioned in the PEP 544's rationale section, it should be fine to treat these built-in abstract classes as protocols.

For now, if mypy doesn't treat a built-in ABC like a protocol where it feels like it should, and the behavior is undocumented/undiscussed elsewhere, it may be worth raising as an issue until the docs for existing builtin protocol-like ABCs are better reconciled with the newer Protocol system.

More generally, until we have something like pure-mixin classes, there won't be a pythonic way to go from normal class to protocol.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 micimize