Skip to content

Commit 960fca1

Browse files
bpo-38979: fix ContextVar "__class_getitem__" method (GH-17497)
now contextvars.ContextVar "__class_getitem__" method returns ContextVar class, not None. https://bugs.python.org/issue38979 Automerge-Triggered-By: @asvetlov (cherry picked from commit 28c9163) Co-authored-by: AMIR <31338382+amiremohamadi@users.noreply.github.com>
1 parent 9d3cacd commit 960fca1

3 files changed

Lines changed: 9 additions & 6 deletions

File tree

Lib/test/test_context.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,6 @@ def test_context_var_new_1(self):
3838

3939
self.assertNotEqual(hash(c), hash('aaa'))
4040

41-
def test_context_var_new_2(self):
42-
self.assertIsNone(contextvars.ContextVar[int])
43-
4441
@isolated_context
4542
def test_context_var_repr_1(self):
4643
c = contextvars.ContextVar('a')
@@ -361,6 +358,10 @@ def sub(num):
361358
tp.shutdown()
362359
self.assertEqual(results, list(range(10)))
363360

361+
def test_contextvar_getitem(self):
362+
clss = contextvars.ContextVar
363+
self.assertEqual(clss[str], clss)
364+
364365

365366
# HAMT Tests
366367

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Return class from ``ContextVar.__class_getitem__`` to simplify subclassing.

Python/context.c

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1010,9 +1010,10 @@ _contextvars_ContextVar_reset(PyContextVar *self, PyObject *token)
10101010

10111011

10121012
static PyObject *
1013-
contextvar_cls_getitem(PyObject *self, PyObject *args)
1013+
contextvar_cls_getitem(PyObject *self, PyObject *arg)
10141014
{
1015-
Py_RETURN_NONE;
1015+
Py_INCREF(self);
1016+
return self;
10161017
}
10171018

10181019
static PyMemberDef PyContextVar_members[] = {
@@ -1025,7 +1026,7 @@ static PyMethodDef PyContextVar_methods[] = {
10251026
_CONTEXTVARS_CONTEXTVAR_SET_METHODDEF
10261027
_CONTEXTVARS_CONTEXTVAR_RESET_METHODDEF
10271028
{"__class_getitem__", contextvar_cls_getitem,
1028-
METH_VARARGS | METH_STATIC, NULL},
1029+
METH_O | METH_CLASS, NULL},
10291030
{NULL, NULL}
10301031
};
10311032

0 commit comments

Comments
 (0)