[issue39778] collections.OrderedDict and weakref.ref raises "refcount is too small" assertion

Pablo Galindo Salgado report at bugs.python.org
Mon Mar 2 10:54:29 EST 2020


Pablo Galindo Salgado <pablogsal at 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 <report at bugs.python.org>
<https://bugs.python.org/issue39778>
_______________________________________


More information about the Python-bugs-list mailing list