diff --git a/Objects/weakrefobject.c b/Objects/weakrefobject.c index 4e119813c717936..d0a53a85c5a95a8 100644 --- a/Objects/weakrefobject.c +++ b/Objects/weakrefobject.c @@ -806,9 +806,17 @@ PyWeakref_NewRef(PyObject *ob, PyObject *callback) */ result = new_weakref(ob, callback); if (result != NULL) { + get_basic_refs(*list, &ref, &proxy); if (callback == NULL) { if (ref == NULL) 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 { PyWeakReference *prev;