Skip to content

Commit 83419e4

Browse files
committed
Add _warnings_context to _warnings module.
1 parent daa3d52 commit 83419e4

File tree

2 files changed

+15
-21
lines changed

2 files changed

+15
-21
lines changed

Include/internal/pycore_warnings.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ struct _warnings_runtime_state {
1616
PyObject *default_action; /* String */
1717
_PyRecursiveMutex lock;
1818
long filters_version;
19+
PyObject *context;
1920
};
2021

2122
extern int _PyWarnings_InitState(PyInterpreterState *interp);

Python/_warnings.c

Lines changed: 14 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ warnings_clear_state(WarningsState *st)
6767
Py_CLEAR(st->filters);
6868
Py_CLEAR(st->once_registry);
6969
Py_CLEAR(st->default_action);
70+
Py_CLEAR(st->context);
7071
}
7172

7273
#ifndef Py_DEBUG
@@ -154,6 +155,13 @@ _PyWarnings_InitState(PyInterpreterState *interp)
154155
}
155156
}
156157

158+
if (st->context == NULL) {
159+
st->context = PyContextVar_New("_warnings_context", NULL);
160+
if (st->context == NULL) {
161+
return -1;
162+
}
163+
}
164+
157165
st->filters_version = 0;
158166
return 0;
159167
}
@@ -257,30 +265,12 @@ warnings_lock_held(WarningsState *st)
257265
static PyObject *
258266
get_warnings_context(PyInterpreterState *interp)
259267
{
260-
PyObject *ctx_var = GET_WARNINGS_ATTR(interp, _warnings_context, 0);
261-
if (ctx_var == NULL) {
262-
if (!PyErr_Occurred()) {
263-
// likely that the 'warnings' module doesn't exist anymore
264-
Py_RETURN_NONE;
265-
}
266-
else {
267-
return NULL;
268-
}
269-
}
270-
if (!PyContextVar_CheckExact(ctx_var)) {
271-
PyErr_Format(PyExc_TypeError,
272-
MODULE_NAME "._warnings_context must be a ContextVar, "
273-
"not '%.200s'",
274-
Py_TYPE(ctx_var)->tp_name);
275-
Py_DECREF(ctx_var);
276-
return NULL;
277-
}
268+
WarningsState *st = warnings_get_state(interp);
269+
assert(PyContextVar_CheckExact(st->context));
278270
PyObject *ctx;
279-
if (PyContextVar_Get(ctx_var, NULL, &ctx) < 0) {
280-
Py_DECREF(ctx_var);
271+
if (PyContextVar_Get(st->context, NULL, &ctx) < 0) {
281272
return NULL;
282273
}
283-
Py_DECREF(ctx_var);
284274
if (ctx == NULL) {
285275
Py_RETURN_NONE;
286276
}
@@ -1652,6 +1642,9 @@ warnings_module_exec(PyObject *module)
16521642
if (PyModule_AddObjectRef(module, "_defaultaction", st->default_action) < 0) {
16531643
return -1;
16541644
}
1645+
if (PyModule_AddObjectRef(module, "_warnings_context", st->context) < 0) {
1646+
return -1;
1647+
}
16551648
return 0;
16561649
}
16571650

0 commit comments

Comments
 (0)