Skip to content

Commit 1f4b728

Browse files
committed
Add PyContextVar_NewThreadInheritable().
1 parent b1795a7 commit 1f4b728

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
@@ -295,18 +295,31 @@ PyContext_Exit(PyObject *octx)
295295
}
296296

297297

298-
PyObject *
299-
PyContextVar_New(const char *name, PyObject *def)
298+
static PyObject *
299+
contextvar_new_from_utf8(const char *name, PyObject *def,
300+
int thread_inheritable)
300301
{
301302
PyObject *pyname = PyUnicode_FromString(name);
302303
if (pyname == NULL) {
303304
return NULL;
304305
}
305-
PyContextVar *var = contextvar_new(pyname, def, 0);
306+
PyContextVar *var = contextvar_new(pyname, def, thread_inheritable);
306307
Py_DECREF(pyname);
307308
return (PyObject *)var;
308309
}
309310

311+
PyObject *
312+
PyContextVar_New(const char *name, PyObject *def)
313+
{
314+
return contextvar_new_from_utf8(name, def, 0);
315+
}
316+
317+
PyObject *
318+
PyContextVar_NewThreadInheritable(const char *name, PyObject *def)
319+
{
320+
return contextvar_new_from_utf8(name, def, 1);
321+
}
322+
310323

311324
int
312325
PyContextVar_Get(PyObject *ovar, PyObject *def, PyObject **val)

0 commit comments

Comments
 (0)