8000 Use a weakref when tracking the "current" module. · python/cpython@3de1cd3 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3de1cd3

Browse files
Use a weakref when tracking the "current" module.
1 parent 5a8b1aa commit 3de1cd3

File tree

1 file changed

+26
-5
lines changed

1 file changed

+26
-5
lines changed

Modules/_datetimemodule.c

Lines changed: 26 additions & 5 deletions
+
}
Original file line numberDiff line numberDiff line change
@@ -107,10 +107,16 @@ get_current_module(PyInterpreterState *interp)
107107
if (dict == NULL) {
108108
return NULL;
109109
}
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) {
112115
return NULL;
113116
}
117+
PyObject *mod = NULL;
118+
(void)PyWeakref_GetRef(ref, &mod);
119+
Py_DECREF(ref);
114120
return mod;
115121
}
116122

@@ -129,26 +135,40 @@ get_current_module(PyInterpreterState *interp)
129135
static int
130136
set_current_module(PyInterpreterState *interp, PyObject *mod)
131137
{
138+
assert(mod != NULL);
132139
PyObject *dict = PyInterpreterState_GetDict(interp);
133140
if (dict == NULL) {
134141
return -1;
135142
}
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;
137150
}
138151

139152
static void
140153
clear_current_module(PyInterpreterState *interp, PyObject *expected)
141154
{
142155
PyObject *exc = PyErr_GetRaisedException();
143156

157+
PyObject *current = NULL;
158+
144159
PyObject *dict = PyInterpreterState_GetDict(interp);
145160
if (dict == NULL) {
146161
goto error;
147162
}
148163

149164
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) {
152172
goto error;
153173
}
154174
if (current != expected) {
@@ -168,6 +188,7 @@ clear_current_module(PyInterpreterState *interp, PyObject *expected)
168188
PyErr_Print();
169189

170190
finally:
191+
Py_XDECREF(current);
171192
PyErr_SetRaisedException(exc);
172193
}
173194

0 commit comments

Comments
 (0)
0