Pablo Galindo Salgado <pablog...@gmail.com> added the comment:

I concur with Antoine and Tim. The GC already has the machinery to deal with 
weak references in the correct way (even more after recent bugfixes regarding 
callbacks). Traversing the weak reference list in incorrect because the object 
does not "own" the weak references to it, as the weak references can die even 
if the object is alive. Also, as Tim mentions, the traverse will be called on 
the head of the list, in the same way if you do object.__weakref__ you will 
only get the HEAD of the list:

>>> import weakref
>>> class A: ...
>>> a = A()
>>> w1 = weakref.ref(a)
>>> w2 = weakref.ref(a, lambda *args: None) # Use a callback to avoid re-using 
>>> the original weakref
>>> id(w1)
4328697104
>>> id(w2)
4328758864
>>> id(a.__weakref__)
4328697104

I think that this is not very well documented, as there is no pointers on what 
should and should not be traversed in 
https://docs.python.org/3.8/c-api/typeobj.html#c.PyTypeObject.tp_traverse.

I will prepare a PR to the documentation if everybody agrees and another one 
removing the traverse unless someone sees that something else is at play.

----------
nosy: +pablogsal

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue39778>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to