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

> The result is that behavioral consistency becomes more difficult in 
> application code when using language provided structures such as 
> WeakValueDictionary.


Well, you are already in tricky territory using finalizers. Note this sentence 
from the docs 
(https://docs.python.org/3/reference/datamodel.html#object.__del__):

> It is not guaranteed that __del__() methods are called for objects that still 
> exist when the interpreter exits.


So CPython does not even promise that __del__ will be called always!


> But doesn't the code above imply that the entry is discarded even though 
> there are strong references to the value?

No, because if there would be strong references then the refcount won't be 0 
and the object would not have been finalized. If the object is finalized is 
because nobody has more strong references. A WeakValueDictionary holds weak 
references in the values, that is why is called WeakValueDictionary ;) 

> In particular, it would be worth pointing out that weakrefs callbacks can run 
> even when the object is referenced.

That can be true but with a big caveat. There are two cases:

- Normal refcount falls to 0: the callback is executed when the deallocator is 
going to run, so nobody has strong references.

- GC: The gc calls the callback *before* the finalizer but at that point 
(before the finalizer) is unreachable from the outside, so all the references 
are from internal objects. Is still referenced but from unreachable objects 
that (unless resurrected) they are going to be destroyed by the gc. Notice that 
at the point the callback runs, all those objects are unreachable, so they 
cannot be referenced by anything in your program except themselves.

----------

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

Reply via email to