Skip to content

Commit 9baa870

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 <[email protected]>
1 parent a197f8a commit 9baa870

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

975975

976976
static PyObject *
977-
contextvar_cls_getitem(PyObject *self, PyObject *args)
977+
contextvar_cls_getitem(PyObject *self, PyObject *arg)
978978
{
979-
Py_RETURN_NONE;
979+
Py_INCREF(self);
980+
return self;
980981
}
981982

982983
static PyMemberDef PyContextVar_members[] = {
@@ -989,7 +990,7 @@ static PyMethodDef PyContextVar_methods[] = {
989990
_CONTEXTVARS_CONTEXTVAR_SET_METHODDEF
990991
_CONTEXTVARS_CONTEXTVAR_RESET_METHODDEF
991992
{"__class_getitem__", contextvar_cls_getitem,
992-
METH_VARARGS | METH_STATIC, NULL},
993+
METH_O | METH_CLASS, NULL},
993994
{NULL, NULL}
994995
};
995996

0 commit comments

Comments
 (0)