Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork33.7k
Description
Various stdlib classes are treated as protocols by type checkers, but are actually ABCs at runtime (for performance reasons). Examples includecontextlib.AbstractContextManager andcollections.abc.Iterable. These classes are special-cased intyping.py to allow for multiple inheritance withtyping.Protocol, so that the interface can be extended:
>>>from contextlibimport AbstractContextManager>>>from typingimport Protocol>>>classFoo(AbstractContextManager,Protocol):...defextra_method(self) ->None:......>>>
collections.abc.Buffer is a new-in-3.12 class that, likeAbstractContextManager andIterable, is an ABC at runtime but will be treated by type checkers as if it were aProtocol. However, multiple inheritance withcollections.abc.Buffer andtyping.Protocol currently fails:
>>>classBar(Buffer,Protocol):...defextra_method(self) ->None:......Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\alexw\coding\cpython\Lib\abc.py", line 106, in __new__ cls = super().__new__(mcls, name, bases, namespace, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\alexw\coding\cpython\Lib\typing.py", line 1916, in __init_subclass__ raise TypeError('Protocols can only inherit from other'TypeError: Protocols can only inherit from other protocols, got <class 'collections.abc.Buffer'>
I thinkBuffer should be special-cased in the same way asBuffer andIterable. It needs to be added to this mapping, I think:
Lines 1740 to 1746 inddb1485
| _PROTO_ALLOWLIST= { | |
| 'collections.abc': [ | |
| 'Callable','Awaitable','Iterable','Iterator','AsyncIterable', | |
| 'Hashable','Sized','Container','Collection','Reversible', | |
| ], | |
| 'contextlib': ['AbstractContextManager','AbstractAsyncContextManager'], | |
| } |
Cc.@JelleZijlstra forPEP-688