Weak References in python

后端 未结 4 2142
醉梦人生
醉梦人生 2021-01-30 10:37

I have been trying to understand how python weak reference lists/dictionaries work. I\'ve read the documentation for it, however I cannot figure out how they work, and what the

4条回答
  •  暖寄归人
    2021-01-30 10:52

    Here is the example comparing dict and WeakValueDictionary:

    class C: pass
    ci=C()
    print(ci)
    
    wvd = weakref.WeakValueDictionary({'key' : ci})
    print(dict(wvd), len(wvd)) #1
    del ci
    print(dict(wvd), len(wvd)) #0
    
    ci2=C()
    d=dict()
    d['key']=ci2
    print(d, len(d))
    del ci2
    print(d, len(d))
    

    And here is the output:

    <__main__.C object at 0x00000213775A1E10>
    {'key': <__main__.C object at 0x00000213775A1E10>} 1
    {} 0
    {'key': <__main__.C object at 0x0000021306B0E588>} 1
    {'key': <__main__.C object at 0x0000021306B0E588>} 1
    

    Note how in the first case once we del ci the actual object will be also removed from the dictionary wvd.

    In the case or regular Python dictionary dict class, we may try to remove the object but it will still be there as shown.


    Note: if we use del, we do not to call gc.collect() after that, since just del effectively removes the object.

提交回复
热议问题