gh-104797: Allow Protocols to inherit from collections.abc.Buffer (#104827)

This commit is contained in:
Jelle Zijlstra 2023-05-24 01:24:53 -07:00 committed by GitHub
parent 4b56e56c49
commit c0ab7d401c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 19 additions and 1 deletions

View file

@ -3546,6 +3546,22 @@ def close(self):
self.assertIsSubclass(B, Custom)
self.assertNotIsSubclass(A, Custom)
@runtime_checkable
class ReleasableBuffer(collections.abc.Buffer, Protocol):
def __release_buffer__(self, mv: memoryview) -> None: ...
class C: pass
class D:
def __buffer__(self, flags: int) -> memoryview:
return memoryview(b'')
def __release_buffer__(self, mv: memoryview) -> None:
pass
self.assertIsSubclass(D, ReleasableBuffer)
self.assertIsInstance(D(), ReleasableBuffer)
self.assertNotIsSubclass(C, ReleasableBuffer)
self.assertNotIsInstance(C(), ReleasableBuffer)
def test_builtin_protocol_allowlist(self):
with self.assertRaises(TypeError):
class CustomProtocol(TestCase, Protocol):

View file

@ -1740,7 +1740,7 @@ def _allow_reckless_class_checks(depth=3):
_PROTO_ALLOWLIST = {
'collections.abc': [
'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer',
],
'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
}

View file

@ -0,0 +1,2 @@
Allow :class:`typing.Protocol` classes to inherit from
:class:`collections.abc.Buffer`. Patch by Jelle Zijlstra.