gh-111926: Simplify weakref creation logic (#116843)

Since 3.12, allocating a GC object cannot immediately trigger GC. This
allows us to simplify the logic for creating the canonical callback-less
weakref.
This commit is contained in:
mpage 2024-03-15 06:56:13 -07:00 committed by GitHub
parent 2cf18a4430
commit 001b21d1c5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 5 additions and 15 deletions

View File

@ -801,24 +801,14 @@ PyWeakref_NewRef(PyObject *ob, PyObject *callback)
if (result != NULL) if (result != NULL)
Py_INCREF(result); Py_INCREF(result);
else { else {
/* Note: new_weakref() can trigger cyclic GC, so the weakref /* We do not need to recompute ref/proxy; new_weakref() cannot
list on ob can be mutated. This means that the ref and trigger GC.
proxy pointers we got back earlier may have been collected, */
so we need to compute these values again before we use
them. */
result = new_weakref(ob, callback); result = new_weakref(ob, callback);
if (result != NULL) { if (result != NULL) {
get_basic_refs(*list, &ref, &proxy);
if (callback == NULL) { if (callback == NULL) {
if (ref == NULL) assert(ref == NULL);
insert_head(result, list); insert_head(result, list);
else {
/* Someone else added a ref without a callback
during GC. Return that one instead of this one
to avoid violating the invariants of the list
of weakrefs for ob. */
Py_SETREF(result, (PyWeakReference*)Py_NewRef(ref));
}
} }
else { else {
PyWeakReference *prev; PyWeakReference *prev;