Skip to content

Commit 7866459

Browse files
mpagevstinner
authored andcommitted
pythongh-111926: Simplify weakref creation logic (python#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.
1 parent 01ef78c commit 7866459

File tree

1 file changed

+5
-15
lines changed

1 file changed

+5
-15
lines changed

Objects/weakrefobject.c

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -801,24 +801,14 @@ PyWeakref_NewRef(PyObject *ob, PyObject *callback)
801801
if (result != NULL)
802802
Py_INCREF(result);
803803
else {
804-
/* Note: new_weakref() can trigger cyclic GC, so the weakref
805-
list on ob can be mutated. This means that the ref and
806-
proxy pointers we got back earlier may have been collected,
807-
so we need to compute these values again before we use
808-
them. */
804+
/* We do not need to recompute ref/proxy; new_weakref() cannot
805+
trigger GC.
806+
*/
809807
result = new_weakref(ob, callback);
810808
if (result != NULL) {
811-
get_basic_refs(*list, &ref, &proxy);
812809
if (callback == NULL) {
813-
if (ref == NULL)
814-
insert_head(result, list);
815-
else {
816-
/* Someone else added a ref without a callback
817-
during GC. Return that one instead of this one
818-
to avoid violating the invariants of the list
819-
of weakrefs for ob. */
820-
Py_SETREF(result, (PyWeakReference*)Py_NewRef(ref));
821-
}
810+
assert(ref == NULL);
811+
insert_head(result, list);
822812
}
823813
else {
824814
PyWeakReference *prev;

0 commit comments

Comments
 (0)