@@ -69,6 +69,7 @@ warnings_clear_state(WarningsState *st)
6969 Py_CLEAR (st -> filters );
7070 Py_CLEAR (st -> once_registry );
7171 Py_CLEAR (st -> default_action );
72+ Py_CLEAR (st -> module );
7273 Py_CLEAR (st -> context );
7374}
7475
@@ -245,8 +246,13 @@ get_warnings_attr(PyInterpreterState *interp, PyObject *attr, int try_import)
245246 return NULL ;
246247 }
247248 warnings_module = PyImport_GetModule (& _Py_ID (warnings ));
248- if (warnings_module == NULL )
249- return NULL ;
249+ if (warnings_module == NULL ) {
250+ WarningsState * st = warnings_get_state (interp );
251+ if (st -> module == NULL ||
252+ PyWeakref_GetRef (st -> module , & warnings_module ) <= 0 ) {
253+ return NULL ;
254+ }
255+ }
250256 }
251257
252258 (void )PyObject_GetOptionalAttr (warnings_module , attr , & obj );
@@ -375,6 +381,25 @@ warnings_release_lock_impl(PyObject *module)
375381 Py_RETURN_NONE ;
376382}
377383
384+ static PyObject *
385+ warnings_set_module (PyObject * Py_UNUSED (module ), PyObject * warnings_module )
386+ {
387+ PyInterpreterState * interp = get_current_interp ();
388+ if (interp == NULL ) {
389+ return NULL ;
390+ }
391+ WarningsState * st = warnings_get_state (interp );
392+ if (st == NULL ) {
393+ return NULL ;
394+ }
395+ PyObject * ref = PyWeakref_NewRef (warnings_module , NULL );
396+ if (ref == NULL ) {
397+ return NULL ;
398+ }
399+ Py_XSETREF (st -> module , ref );
400+ Py_RETURN_NONE ;
401+ }
402+
378403static PyObject *
379404get_once_registry (PyInterpreterState * interp )
380405{
@@ -1593,6 +1618,7 @@ static PyMethodDef warnings_functions[] = {
15931618 WARNINGS_FILTERS_MUTATED_LOCK_HELD_METHODDEF
15941619 WARNINGS_ACQUIRE_LOCK_METHODDEF
15951620 WARNINGS_RELEASE_LOCK_METHODDEF
1621+ {"_set_module" , warnings_set_module , METH_O , NULL },
15961622 /* XXX(brett.cannon): add showwarning? */
15971623 /* XXX(brett.cannon): Reasonable to add formatwarning? */
15981624 {NULL , NULL } /* sentinel */
0 commit comments