@@ -107,10 +107,16 @@ get_current_module(PyInterpreterState *interp)
107
107
if (dict == NULL ) {
108
108
return NULL ;
109
109
}
110
- PyObject * mod = NULL ;
111
- if (PyDict_GetItemStringRef (dict , INTERP_KEY , & mod ) < 0 ) {
110
+ PyObject * ref = NULL ;
111
+ if (PyDict_GetItemStringRef (dict , INTERP_KEY , & ref ) < 0 ) {
112
+ return NULL ;
113
+ }
114
+ if (ref == NULL ) {
112
115
return NULL ;
113
116
}
117
+ PyObject * mod = NULL ;
118
+ (void )PyWeakref_GetRef (ref , & mod );
119
+ Py_DECREF (ref );
114
120
return mod ;
115
121
}
116
122
@@ -129,26 +135,40 @@ get_current_module(PyInterpreterState *interp)
129
135
static int
130
136
set_current_module (PyInterpreterState * interp , PyObject * mod )
131
137
{
138
+ assert (mod != NULL );
132
139
PyObject * dict = PyInterpreterState_GetDict (interp );
133
140
if (dict == NULL ) {
134
141
return -1 ;
135
142
}
136
- return PyDict_SetItemString (dict , INTERP_KEY , mod );
143
+ PyObject * ref = PyWeakref_NewRef (mod , NULL );
144
+ if (ref == NULL ) {
145
+ return -1 ;
146
+ }
147
+ int rc = PyDict_SetItemString (dict , INTERP_KEY , ref );
148
+ Py_DECREF (ref );
149
+ return rc ;
137
150
}
138
151
139
152
static void
140
153
clear_current_module (PyInterpreterState * interp , PyObject * expected )
141
154
{
142
155
PyObject * exc = PyErr_GetRaisedException ();
143
156
157
+ PyObject * current = NULL ;
158
+
144
159
PyObject * dict = PyInterpreterState_GetDict (interp );
145
160
if (dict == NULL ) {
146
161
goto error ;
147
162
}
148
163
149
164
if (expected != NULL ) {
150
- PyObject * current = NULL ;
151
- if (PyDict_GetItemStringRef (dict , INTERP_KEY , & current ) < 0 ) {
165
+ PyObject * ref = NULL ;
166
+ if (PyDict_GetItemStringRef (dict , INTERP_KEY , & ref ) < 0 ) {
167
+ goto error ;
168
+ }
169
+ int rc = PyWeakref_GetRef (ref , & current );
170
+ Py_DECREF (ref );
171
+ if (rc < 0 ) {
152
172
goto error ;
153
173
}
154
174
if (current != expected ) {
@@ -168,6 +188,7 @@ clear_current_module(PyInterpreterState *interp, PyObject *expected)
168
188
PyErr_Print ();
169
189
170
190
finally :
191
+ Py_XDECREF (current );
171
192
PyErr_SetRaisedException (exc );
172
193
}
173
194
0 commit comments