Skip to content

Commit c214680

Browse files
committed
Implement context manager for Token
1 parent 4c14f03 commit c214680

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

Lib/test/test_context.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -383,6 +383,31 @@ def sub(num):
383383
tp.shutdown()
384384
self.assertEqual(results, list(range(10)))
385385

386+
def test_token_contextmanager_with_default(self):
387+
ctx = contextvars.Context()
388+
c = contextvars.ContextVar('c', default=42)
389+
390+
def fun():
391+
with c.set(36):
392+
self.assertEqual(c.get(), 36)
393+
394+
self.assertEqual(c.get(), 42)
395+
396+
ctx.run(fun)
397+
398+
def test_token_contextmanager_without_default(self):
399+
ctx = contextvars.Context()
400+
c = contextvars.ContextVar('c')
401+
402+
def fun():
403+
with c.set(36):
404+
self.assertEqual(c.get(), 36)
405+
406+
with self.assertRaisesRegex(LookupError, "<ContextVar name='c'"):
407+
c.get()
408+
409+
ctx.run(fun)
410+
386411

387412
# HAMT Tests
388413

Python/context.c

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1216,9 +1216,29 @@ static PyGetSetDef PyContextTokenType_getsetlist[] = {
12161216
{NULL}
12171217
};
12181218

1219+
static PyObject *
1220+
token_enter(PyContextToken *self, PyObject *args)
1221+
{
1222+
return Py_NewRef(self);
1223+
}
1224+
1225+
static PyObject *
1226+
token_exit(PyContextToken *self, PyObject *args)
1227+
{
1228+
int ret = PyContextVar_Reset((PyObject *)self->tok_var, (PyObject *)self);
1229+
if (ret < 0) {
1230+
return NULL;
1231+
}
1232+
Py_RETURN_NONE;
1233+
}
1234+
12191235
static PyMethodDef PyContextTokenType_methods[] = {
12201236
{"__class_getitem__", Py_GenericAlias,
12211237
METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
1238+
1239+
{"__enter__", (PyCFunction)token_enter, METH_NOARGS, NULL},
1240+
{"__exit__", (PyCFunction)token_exit, METH_VARARGS, NULL},
1241+
12221242
{NULL}
12231243
};
12241244

0 commit comments

Comments
 (0)