]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.12] gh-104797: Allow Protocols to inherit from collections.abc.Buffer (GH-104827...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Wed, 24 May 2023 09:05:34 +0000 (02:05 -0700)
committerGitHub <noreply@github.com>
Wed, 24 May 2023 09:05:34 +0000 (09:05 +0000)
gh-104797: Allow Protocols to inherit from collections.abc.Buffer (GH-104827)
(cherry picked from commit c0ab7d401c736c37bf4462eef7c7d69fef8fab93)

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Lib/test/test_typing.py
Lib/typing.py
Misc/NEWS.d/next/Library/2023-05-23-17-43-52.gh-issue-104797.NR7KzF.rst [new file with mode: 0644]

index 9a3e64289ee8778d97dd69232959fa92b3383453..a3fad6f35e7136c7c75fcac880ccddc14d5f15ac 100644 (file)
@@ -3546,6 +3546,22 @@ class ProtocolTests(BaseTestCase):
         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):
index 96393d6a02815b6a3517de14d20bad9fe3d2c875..88837db4b744ab594d5be150420d4457fd235294 100644 (file)
@@ -1745,7 +1745,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'],
 }
diff --git a/Misc/NEWS.d/next/Library/2023-05-23-17-43-52.gh-issue-104797.NR7KzF.rst b/Misc/NEWS.d/next/Library/2023-05-23-17-43-52.gh-issue-104797.NR7KzF.rst
new file mode 100644 (file)
index 0000000..60c9a06
--- /dev/null
@@ -0,0 +1,2 @@
+Allow :class:`typing.Protocol` classes to inherit from
+:class:`collections.abc.Buffer`. Patch by Jelle Zijlstra.