Skip to content

Commit 28c9163

Browse files
amiremohamadimiss-islington
authored andcommitted
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
1 parent 00ada2c commit 28c9163

File tree

3 files changed

+9
-6
lines changed

3 files changed

+9
-6
lines changed

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
@@ -1024,9 +1024,10 @@ _contextvars_ContextVar_reset(PyContextVar *self, PyObject *token)
10241024

10251025

10261026
static PyObject *
1027-
contextvar_cls_getitem(PyObject *self, PyObject *args)
1027+
contextvar_cls_getitem(PyObject *self, PyObject *arg)
10281028
{
1029-
Py_RETURN_NONE;
1029+
Py_INCREF(self);
1030+
return self;
10301031
}
10311032

10321033
static PyMemberDef PyContextVar_members[] = {
@@ -1039,7 +1040,7 @@ static PyMethodDef PyContextVar_methods[] = {
10391040
_CONTEXTVARS_CONTEXTVAR_SET_METHODDEF
10401041
_CONTEXTVARS_CONTEXTVAR_RESET_METHODDEF
10411042
{"__class_getitem__", contextvar_cls_getitem,
1042-
METH_VARARGS | METH_STATIC, NULL},
1043+
METH_O | METH_CLASS, NULL},
10431044
{NULL, NULL}
10441045
};
10451046

0 commit comments

Comments
 (0)