Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add PyContextVar_NewThreadInheritable().
  • Loading branch information
nascheme committed Jul 24, 2026
commit 1f4b728066716ee9b9ed72a9fd968d2fabea3afa
8 changes: 8 additions & 0 deletions Doc/c-api/contextvars.rst
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,14 @@ Context variable functions:
a default value for the context variable, or ``NULL`` for no default.
If an error has occurred, this function returns ``NULL``.

.. c:function:: PyObject *PyContextVar_NewThreadInheritable(const char *name, PyObject *def)

Create a new ``ContextVar`` object whose bindings are inherited by new
:class:`threading.Thread` instances. The parameters and return value are
the same as for :c:func:`PyContextVar_New`.

.. versionadded:: 3.16

.. c:function:: int PyContextVar_Get(PyObject *var, PyObject *default_value, PyObject **value)

Get the value of a context variable. Returns ``-1`` if an error has
Expand Down
7 changes: 7 additions & 0 deletions Include/cpython/context.h
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,13 @@ PyAPI_FUNC(int) PyContext_ClearWatcher(int watcher_id);
PyAPI_FUNC(PyObject *) PyContextVar_New(
const char *name, PyObject *default_value);

/* Create a new thread-inheritable context variable.

default_value can be NULL.
*/
PyAPI_FUNC(PyObject *) PyContextVar_NewThreadInheritable(
const char *name, PyObject *default_value);


/* Get a value for the variable.

Expand Down
19 changes: 16 additions & 3 deletions Python/context.c
Original file line number Diff line number Diff line change
Expand Up @@ -295,18 +295,31 @@ PyContext_Exit(PyObject *octx)
}


PyObject *
PyContextVar_New(const char *name, PyObject *def)
static PyObject *
contextvar_new_from_utf8(const char *name, PyObject *def,
int thread_inheritable)
{
PyObject *pyname = PyUnicode_FromString(name);
if (pyname == NULL) {
return NULL;
}
PyContextVar *var = contextvar_new(pyname, def, 0);
PyContextVar *var = contextvar_new(pyname, def, thread_inheritable);
Py_DECREF(pyname);
return (PyObject *)var;
}

PyObject *
PyContextVar_New(const char *name, PyObject *def)
{
return contextvar_new_from_utf8(name, def, 0);
}

PyObject *
PyContextVar_NewThreadInheritable(const char *name, PyObject *def)
{
return contextvar_new_from_utf8(name, def, 1);
}


int
PyContextVar_Get(PyObject *ovar, PyObject *def, PyObject **val)
Expand Down