Search code examples
pythonweak-references

Python, inconsistent results vs docs: object deleted but weak ref still 'active'


There are many questions out there regarding this subject which I already checked. Example dated 2014!

One can also find the 'canonical' documentation here.

I don't know why I cannot reproduce the docs:

import weakref, gc
class A:
    pass
a = A()
b = weakref.ref(a)
a
Out[5]: <__main__.A at 0x250f782f3a0>
b()
Out[6]: <__main__.A at 0x250f782f3a0>
del a
b()
Out[8]: <__main__.A at 0x250f782f3a0>
gc.collect()
Out[9]: 9
b()
Out[10]: <__main__.A at 0x250f782f3a0>

b should be returning None but is not.

EDIT

Interestingly, this question on which I am interested as well, remains unanswered since a couple of years as well. Just tagging in case somebody can address both in one shot.

(Windows 10, python 3.8, Conda env)


Solution

  • I tried what was mentioned in the comments to the question and am posting an answer for documentation purposes. Running the said code in the REPL was the problem.

    What I tried:

    test.py:

    if __name__ == '__main__':
        import weakref, gc
        class A: pass
        a = A()
        b = weakref.ref(a)
        print("a: ", a)
        print("b(): ", b())
        del a
        print("b(): ", b())
        gc.collect()
        print("b(): ", b())
    

    $ python test.py:

    a:  <__main__.A object at 0x000002678F96A400>
    b():  <__main__.A object at 0x000002678F96A400>
    b():  None
    b():  None
    
    Process finished with exit code 0
    

    So it does work as documented.