Skip to content

Commit d71da0f

Browse files
miss-islingtontungolsobolevnAlexWaygoodZeroIntensity
authored
[3.12] gh-126451: Register contextvars.Context to collections.abc.Mapping (GH-126452) (#126519)
gh-126451: Register contextvars.Context to collections.abc.Mapping (GH-126452) (cherry picked from commit 5dc36dc) Co-authored-by: Stephen Morton <[email protected]> Co-authored-by: sobolevn <[email protected]> Co-authored-by: Alex Waygood <[email protected]> Co-authored-by: Peter Bierma <[email protected]>
1 parent a19832b commit d71da0f

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

Lib/contextvars.py

+4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1+
import _collections_abc
12
from _contextvars import Context, ContextVar, Token, copy_context
23

34

45
__all__ = ('Context', 'ContextVar', 'Token', 'copy_context')
6+
7+
8+
_collections_abc.Mapping.register(Context)

Lib/test/test_context.py

+14
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import collections.abc
12
import concurrent.futures
23
import contextvars
34
import functools
@@ -342,6 +343,19 @@ def ctx2_fun():
342343

343344
ctx1.run(ctx1_fun)
344345

346+
def test_context_isinstance(self):
347+
ctx = contextvars.Context()
348+
self.assertIsInstance(ctx, collections.abc.Mapping)
349+
self.assertTrue(issubclass(contextvars.Context, collections.abc.Mapping))
350+
351+
mapping_methods = (
352+
'__contains__', '__eq__', '__getitem__', '__iter__', '__len__',
353+
'__ne__', 'get', 'items', 'keys', 'values',
354+
)
355+
for name in mapping_methods:
356+
with self.subTest(name=name):
357+
self.assertTrue(callable(getattr(ctx, name)))
358+
345359
@isolated_context
346360
@threading_helper.requires_working_threading()
347361
def test_context_threads_1(self):
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Register the :class:`contextvars.Context` type to
2+
:class:`collections.abc.Mapping`.

0 commit comments

Comments
 (0)