Skip to content

Commit f38695a

Browse files
committed
Add PyContextVar_NewThreadInheritable().
1 parent c29fef5 commit f38695a

3 files changed

Lines changed: 31 additions & 3 deletions

File tree

Doc/c-api/contextvars.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,14 @@ Context variable functions:
157157
a default value for the context variable, or ``NULL`` for no default.
158158
If an error has occurred, this function returns ``NULL``.
159159
160+
.. c:function:: PyObject *PyContextVar_NewThreadInheritable(const char *name, PyObject *def)
161+
162+
Create a new ``ContextVar`` object whose bindings are inherited by new
163+
:class:`threading.Thread` instances. The parameters and return value are
164+
the same as for :c:func:`PyContextVar_New`.
165+
166+
.. versionadded:: 3.16
167+
160168
.. c:function:: int PyContextVar_Get(PyObject *var, PyObject *default_value, PyObject **value)
161169
162170
Get the value of a context variable. Returns ``-1`` if an error has

Include/cpython/context.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,13 @@ PyAPI_FUNC(int) PyContext_ClearWatcher(int watcher_id);
6868
PyAPI_FUNC(PyObject *) PyContextVar_New(
6969
const char *name, PyObject *default_value);
7070

71+
/* Create a new thread-inheritable context variable.
72+
73+
default_value can be NULL.
74+
*/
75+
PyAPI_FUNC(PyObject *) PyContextVar_NewThreadInheritable(
76+
const char *name, PyObject *default_value);
77+
7178

7279
/* Get a value for the variable.
7380

Python/context.c

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -281,18 +281,31 @@ PyContext_Exit(PyObject *octx)
281281
}
282282

283283

284-
PyObject *
285-
PyContextVar_New(const char *name, PyObject *def)
284+
static PyObject *
285+
contextvar_new_from_utf8(const char *name, PyObject *def,
286+
int thread_inheritable)
286287
{
287288
PyObject *pyname = PyUnicode_FromString(name);
288289
if (pyname == NULL) {
289290
return NULL;
290291
}
291-
PyContextVar *var = contextvar_new(pyname, def, 0);
292+
PyContextVar *var = contextvar_new(pyname, def, thread_inheritable);
292293
Py_DECREF(pyname);
293294
return (PyObject *)var;
294295
}
295296

297+
PyObject *
298+
PyContextVar_New(const char *name, PyObject *def)
299+
{
300+
return contextvar_new_from_utf8(name, def, 0);
301+
}
302+
303+
PyObject *
304+
PyContextVar_NewThreadInheritable(const char *name, PyObject *def)
305+
{
306+
return contextvar_new_from_utf8(name, def, 1);
307+
}
308+
296309

297310
int
298311
PyContextVar_Get(PyObject *ovar, PyObject *def, PyObject **val)

0 commit comments

Comments
 (0)