Skip to content

Commit c0ab7d4

Browse files
gh-104797: Allow Protocols to inherit from collections.abc.Buffer (#104827)
1 parent 4b56e56 commit c0ab7d4

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

Lib/test/test_typing.py

Lines changed: 16 additions & 0 deletions
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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1740,7 +1740,7 @@ def _allow_reckless_class_checks(depth=3):
17401740
_PROTO_ALLOWLIST = {
17411741
'collections.abc': [
17421742
'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
1743-
'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
1743+
'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer',
17441744
],
17451745
'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
17461746
}
Lines changed: 2 additions & 0 deletions
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)