If you were only trying to do this in an interactive shell, I suppose this is due to how garbage collection works in this interface and in global operations.
Try this from the script:
foo.py
from weakref import WeakValueDictionary class Foo(object): pass f = Foo() d = WeakValueDictionary() d['f'] = f print dict(d) del f print dict(d)
And then...
$ python foo.py {'f': <__main__.Foo object at 0x101f496d0>} {}
Now try this from the python interactive shell, moving the operation in the scope of functions:
from weakref import WeakValueDictionary class Foo(object): pass f = Foo() d = WeakValueDictionary() d['f'] = f def main(): global f print dict(d) del f print dict(d) main()
source share