@@ -1558,18 +1558,23 @@ finalize_remove_modules(PyObject *modules, int verbose)
15581558 if (weaklist != NULL) { \
15591559 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
15601560 if (wr) { \
1561- PyObject *list = Py_REFCNT(wr) <= 1 ? weaklist : weak_ext; \
1562- PyObject *tup = PyTuple_Pack(2, name, wr); \
1563- if (!tup || PyList_Append(list, tup) < 0) { \
1564- PyErr_FormatUnraisable("Exception ignored while removing modules"); \
1565- } \
1566- if (list == weak_ext) { \
1561+ PyObject *list; \
1562+ PyObject *tup; \
1563+ if (Py_REFCNT(wr) > 1) { \
15671564 /* gh-132413: When the weakref is already used elsewhere,
15681565 * finalize_modules_clear_weaklist() rather than the GC
15691566 * should clear the referenced module since the GC tries
15701567 * to clear the wrakref first. The weaklist requires the
15711568 * order in which such modules are cleared first. */ \
1572- _PyObject_GC_UNTRACK (mod ); \
1569+ tup = PyTuple_Pack (3 , name , wr , mod ); \
1570+ list = weak_ext ; \
1571+ } \
1572+ else { \
1573+ tup = PyTuple_Pack (2 , name , wr ); \
1574+ list = weaklist ; \
1575+ } \
1576+ if (!tup || PyList_Append (list , tup ) < 0 ) { \
1577+ PyErr_FormatUnraisable ("Exception ignored while removing modules" ); \
15731578 } \
15741579 Py_XDECREF (tup ); \
15751580 Py_DECREF (wr ); \
@@ -1678,9 +1683,6 @@ finalize_modules_clear_weaklist(PyInterpreterState *interp,
16781683 continue ;
16791684 }
16801685 assert (PyModule_Check (mod ));
1681- if (!_PyObject_GC_IS_TRACKED (mod )) {
1682- _PyObject_GC_TRACK (mod );
1683- }
16841686 PyObject * dict = _PyModule_GetDict (mod ); // borrowed reference
16851687 if (dict == interp -> builtins || dict == interp -> sysdict ) {
16861688 Py_DECREF (mod );
0 commit comments