]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-126451: Register contextvars.Context to collections.abc.Mapping (#126452)
authorStephen Morton <git@tungol.org>
Wed, 6 Nov 2024 22:12:45 +0000 (14:12 -0800)
committerGitHub <noreply@github.com>
Wed, 6 Nov 2024 22:12:45 +0000 (01:12 +0300)
Co-authored-by: sobolevn <mail@sobolevn.me>
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
Lib/contextvars.py
Lib/test/test_context.py
Misc/NEWS.d/next/Library/2024-11-05-11-28-45.gh-issue-126451.XJMtqz.rst [new file with mode: 0644]

index d78c80dfe6f99cefe1a875b16a9e7296546636fe..14514f185e069dd60ec521f7f5a579c10f1d802c 100644 (file)
@@ -1,4 +1,8 @@
+import _collections_abc
 from _contextvars import Context, ContextVar, Token, copy_context
 
 
 __all__ = ('Context', 'ContextVar', 'Token', 'copy_context')
+
+
+_collections_abc.Mapping.register(Context)
index b06b9df9f5b0b8a5b665df16e3a1b537b541264c..82d1797ab3b79e2945db8440962f27f33fd7c3d4 100644 (file)
@@ -1,3 +1,4 @@
+import collections.abc
 import concurrent.futures
 import contextvars
 import functools
@@ -350,6 +351,19 @@ class ContextTest(unittest.TestCase):
 
         ctx1.run(ctx1_fun)
 
+    def test_context_isinstance(self):
+        ctx = contextvars.Context()
+        self.assertIsInstance(ctx, collections.abc.Mapping)
+        self.assertTrue(issubclass(contextvars.Context, collections.abc.Mapping))
+
+        mapping_methods = (
+            '__contains__', '__eq__', '__getitem__', '__iter__', '__len__',
+            '__ne__', 'get', 'items', 'keys', 'values',
+        )
+        for name in mapping_methods:
+            with self.subTest(name=name):
+                self.assertTrue(callable(getattr(ctx, name)))
+
     @isolated_context
     @threading_helper.requires_working_threading()
     def test_context_threads_1(self):
diff --git a/Misc/NEWS.d/next/Library/2024-11-05-11-28-45.gh-issue-126451.XJMtqz.rst b/Misc/NEWS.d/next/Library/2024-11-05-11-28-45.gh-issue-126451.XJMtqz.rst
new file mode 100644 (file)
index 0000000..563cb25
--- /dev/null
@@ -0,0 +1,2 @@
+Register the :class:`contextvars.Context` type to
+:class:`collections.abc.Mapping`.