Skip to content

Commit

Permalink
Implement context manager for Token
Browse files Browse the repository at this point in the history
  • Loading branch information
asvetlov committed Jan 3, 2025
1 parent 4c14f03 commit c214680
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
25 changes: 25 additions & 0 deletions Lib/test/test_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,31 @@ def sub(num):
tp.shutdown()
self.assertEqual(results, list(range(10)))

def test_token_contextmanager_with_default(self):
ctx = contextvars.Context()
c = contextvars.ContextVar('c', default=42)

def fun():
with c.set(36):
self.assertEqual(c.get(), 36)

self.assertEqual(c.get(), 42)

ctx.run(fun)

def test_token_contextmanager_without_default(self):
ctx = contextvars.Context()
c = contextvars.ContextVar('c')

def fun():
with c.set(36):
self.assertEqual(c.get(), 36)

with self.assertRaisesRegex(LookupError, "<ContextVar name='c'"):
c.get()

ctx.run(fun)


# HAMT Tests

Expand Down
20 changes: 20 additions & 0 deletions Python/context.c
Original file line number Diff line number Diff line change
Expand Up @@ -1216,9 +1216,29 @@ static PyGetSetDef PyContextTokenType_getsetlist[] = {
{NULL}
};

static PyObject *
token_enter(PyContextToken *self, PyObject *args)
{
return Py_NewRef(self);
}

static PyObject *
token_exit(PyContextToken *self, PyObject *args)
{
int ret = PyContextVar_Reset((PyObject *)self->tok_var, (PyObject *)self);
if (ret < 0) {
return NULL;
}
Py_RETURN_NONE;
}

static PyMethodDef PyContextTokenType_methods[] = {
{"__class_getitem__", Py_GenericAlias,
METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},

{"__enter__", (PyCFunction)token_enter, METH_NOARGS, NULL},
{"__exit__", (PyCFunction)token_exit, METH_VARARGS, NULL},

{NULL}
};

Expand Down

0 comments on commit c214680

Please sign in to comment.