Skip to content

Commit 42a05db

Browse files
JelleZijlstramiss-islington
authored andcommitted
pythongh-104797: Allow Protocols to inherit from collections.abc.Buffer (pythonGH-104827)
(cherry picked from commit c0ab7d4) Co-authored-by: Jelle Zijlstra <[email protected]>
1 parent b719dd8 commit 42a05db

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

Lib/test/test_typing.py

+16
Original file line numberDiff line numberDiff line change
@@ -3546,6 +3546,22 @@ def close(self):
35463546
self.assertIsSubclass(B, Custom)
35473547
self.assertNotIsSubclass(A, Custom)
35483548

3549+
@runtime_checkable
3550+
class ReleasableBuffer(collections.abc.Buffer, Protocol):
3551+
def __release_buffer__(self, mv: memoryview) -> None: ...
3552+
3553+
class C: pass
3554+
class D:
3555+
def __buffer__(self, flags: int) -> memoryview:
3556+
return memoryview(b'')
3557+
def __release_buffer__(self, mv: memoryview) -> None:
3558+
pass
3559+
3560+
self.assertIsSubclass(D, ReleasableBuffer)
3561+
self.assertIsInstance(D(), ReleasableBuffer)
3562+
self.assertNotIsSubclass(C, ReleasableBuffer)
3563+
self.assertNotIsInstance(C(), ReleasableBuffer)
3564+
35493565
def test_builtin_protocol_allowlist(self):
35503566
with self.assertRaises(TypeError):
35513567
class CustomProtocol(TestCase, Protocol):

Lib/typing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1745,7 +1745,7 @@ def _allow_reckless_class_checks(depth=3):
17451745
_PROTO_ALLOWLIST = {
17461746
'collections.abc': [
17471747
'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
1748-
'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
1748+
'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer',
17491749
],
17501750
'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
17511751
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Allow :class:`typing.Protocol` classes to inherit from
2+
:class:`collections.abc.Buffer`. Patch by Jelle Zijlstra.

0 commit comments

Comments
 (0)