[issue40312] Weakref callbacks running before finalizers in GC collection

Allan Feldman report at bugs.python.org
Mon Apr 20 14:54:19 EDT 2020


Allan Feldman <allan.d.feldman at gmail.com> added the comment:

Yup agree with all the points above, just wanted to point out that I think self.value is strongly referenced (even though it's just internal references and will be collected by the gc) during Foo.__del__ execution (annotated code below), yet the WeakValueDictionary entry is cleared:

import gc
import sys
import weakref

cache = weakref.WeakValueDictionary()


class Bar:
    pass


class Foo:
    def __init__(self):
        self._self = self
        self.value = Bar()
        cache[id(self.value)] = self.value

    def __del__(self):
        print(sys.getrefcount(self.value))  # -> 2
        # the cache may or may not have self.value at this point
        # even though self.value is strongly referenced!
        print(list(cache.items()))  # -> []


o = Foo()
del o
gc.collect()

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue40312>
_______________________________________


More information about the Python-bugs-list mailing list